Checkpoint

This commit is contained in:
maze authored and maze committed 2026-10-29 17:29:54 +01:00
1 parent c5d6137fab
commit 4ae7655cd8
223 files changed
+14753 -18335

No files matched your search

+28
View File
@@ -1,3 +1,31 @@
# Allowlisting gitignore template for Go projects prevents us
# from adding various unwanted local files, such as generated
# files, developer configurations or IDE-specific files etc.
#
# Recommended: Go.AllowList.gitignore
# Ignore everything
*
# But not these files...
!/.gitignore
!*.go
!go.sum
!go.mod
!README.md
!LICENSE
# !Makefile
# ...even if they are in subdirectories
!*/
# Explicity ignore cruft
_old/
# Go build artifacts and local environment files
# ---> Go
# If you prefer the allow list template instead of the deny list, see community template:
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
+15 -10
View File
@@ -1,23 +1,28 @@
GO_BUILD := go build -ldflags="-w -s" \
-gcflags=-trimpath=/Users/myuser/dev/go/src \
-asmflags=-trimpath=/Users/myuser/dev/go/src \
GO_BUILD := go build \
-trimpath \
-ldflags="-w -s" \
-gcflags=-trimpath="$(shell pwd)" \
-asmflags=-trimpath="$(shell pwd)" \
SOURCES := $(wildcard *.go) \
$(wildcard app/*.go) \
$(wildcard app/*/*.go) \
$(wildcard hardware/*.go) \
$(wildcard hardware/display/*.go) \
$(wildcard hardware/display/*/*.go) \
$(wildcard hardware/*/*.go) \
$(wildcard hardware/*/*/*.go) \
$(wildcard config/*.go) \
$(wildcard internal/*/*.go) \
$(wildcard audio/*.go) \
$(wildcard visual/*/*.go) \
$(wildcard sound/*.go) \
$(wildcard player/*.go) \
$(wildcard player/*/*.go)
BINARY := beatglow
.PHONY:
harmon: $(SOURCES)
GOOS=linux GOARCH=arm $(GO_BUILD) -o $@ ./cmd/harmon
$(BINARY): $(SOURCES)
GOOS=linux GOARCH=arm $(GO_BUILD) -o $@ ./cmd/$(BINARY)
clean:
$(RM) harmon
$(RM) $(BINARY)
+27 -7
View File
@@ -3,13 +3,22 @@ package app
import (
"image"
"github.com/BeatGlow/beatglow/player"
"github.com/BeatGlow/audio"
"github.com/BeatGlow/display"
"github.com/BeatGlow/beatglow/config"
"github.com/BeatGlow/beatglow/player"
)
type Layout interface {
String() string
// Hide the layout
Hide(Context)
// Show the layout.
Show(Context)
// Widgets used by this screen.
Widgets() []Widget
}
@@ -23,6 +32,12 @@ type Context interface {
// Track is the current track playing.
Track() *player.Track
// Show switches layout.
Show(Layout)
// Settings are the user settings.
Settings() *config.Settings
}
type Widget interface {
@@ -46,22 +61,27 @@ type Widget interface {
// IsVisible checks if the drawable is visible.
IsVisible() bool
Refresh(Context) Widget
// Refresh redraws the widget if it's in view.
Refresh(Context) bool
}
type RotaryInputHandler interface {
HandleRotary(delta int)
HandleRotary(ctx Context, delta int)
}
type ButtonInputHandler interface {
HandleButtonPress()
HandleButtonLongPress()
HandleButtonPress(Context)
HandleButtonLongPress(Context)
}
type StatusChangeHandler interface {
StatusChanged(*player.Status)
StatusChanged(Context, *player.Status)
}
type TrackChangeHandler interface {
TrackChanged(*player.Track)
TrackChanged(Context, *player.Track)
}
type BufferProcessor interface {
ProcessBuffer(audio.Buffer[float64])
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+45
View File
@@ -0,0 +1,45 @@
The work in the Hack project is Copyright 2018 Source Foundry Authors and licensed under the MIT License
The work in the DejaVu project was committed to the public domain.
Bitstream Vera Sans Mono Copyright 2003 Bitstream Inc. and licensed under the Bitstream Vera License with Reserved Font Names "Bitstream" and "Vera"
### MIT License
Copyright (c) 2018 Source Foundry Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
### BITSTREAM VERA LICENSE
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license ("Fonts") and associated documentation files (the "Font Software"), to reproduce and distribute the Font Software, including without limitation the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so, subject to the following conditions:
The above copyright and trademark notices and this permission notice shall be included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing either the words "Bitstream" or the word "Vera".
This License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed under the "Bitstream Vera" names.
The Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be sold by itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
Except as contained in this notice, the names of Gnome, the Gnome Foundation, and Bitstream Inc., shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Font Software without prior written authorization from the Gnome Foundation or Bitstream Inc., respectively. For further information, contact: fonts at gnome dot org.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+43
View File
@@ -0,0 +1,43 @@
package font
import _ "embed"
var (
//go:embed asset/sm4tik.bdf
sm4tikBDF []byte
//go:embed asset/siji.bdf
sijiBDF []byte
//go:embed asset/spleen-5x8.bdf
spleen5x8BDF []byte
//go:embed asset/spleen-6x12.bdf
spleen6x12BDF []byte
//go:embed asset/spleen-8x16.bdf
spleen8x16BDF []byte
)
var (
//go:embed asset/HackNerdFontMono-Regular.ttf
hackMonoTTF []byte
//go:embed asset/Mairy-BlackItalic.ttf
mairyBlackItalicTTF []byte
//go:embed asset/MicroGrotesk.ttf
microgroteskTTF []byte
//go:embed asset/Monaco.ttf
monacoRegularTTF []byte
//go:embed asset/Montserrat.ttf
montserratTTF []byte
//go:embed asset/Montserrat-Italic.ttf
montserratItalicTTF []byte
//go:embed asset/SmoochSans-Regular.ttf
smoochSansTTF []byte
)
+151
View File
@@ -0,0 +1,151 @@
package font
import (
"bytes"
"fmt"
"image"
"math"
"os"
"github.com/golang/freetype/truetype"
"github.com/sirupsen/logrus"
"github.com/zachomedia/go-bdf"
"golang.org/x/image/font"
"golang.org/x/image/font/opentype"
"github.com/BeatGlow/display/draw"
)
// Fonts contained
var (
HackMono = Must(NewFromBytes(hackMonoTTF))
MairyBlackItalic = Must(NewFromBytes(mairyBlackItalicTTF))
MicroGrotesk = Must(NewFromBytes(microgroteskTTF))
Monaco = Must(NewFromBytes(monacoRegularTTF))
Montserrat = Must(NewFromBytes(montserratTTF))
MontserratItalic = Must(NewFromBytes(montserratItalicTTF))
SmoochSans = Must(NewFromBytes(smoochSansTTF))
)
type Font interface {
Draw(dst draw.Image, p image.Point, fg image.Image, text string)
MeasureString(string) (width, height int)
// SetHintint changes the hinting.
SetHinting(hinting Hinting) Font
// SetDPI changes the dots-per-inch.
SetDPI(float64) Font
// SetPointSize changes the point size.
SetPointSize(float64) Font
// WithDPI returns a copy of the font with the requested dots-per-inch.
WithDPI(float64) Font
// WithPointSize returns a copy of the font with the requested point size.
WithPointSize(float64) Font
}
func Must(font Font, err error) Font {
if err != nil {
panic(err)
}
return font
}
type FontAttr struct {
PointSize float64 // Point size of the font
DPI float64 // Resolution of the font in dots per inch
LineSpacing float64 // Spacing between lines (in terms of font height)
Hinting font.Hinting // Font hinting
}
// Hinting is a type alias.
type Hinting = font.Hinting
const (
HintingNone = font.HintingNone
HintingVertical = font.HintingVertical
HintingFull = font.HintingFull
)
func (a *FontAttr) newTTOptions(scaleX, scaleY float64) *truetype.Options {
dpi := a.DPI
if scaleX*scaleY != 0 {
dpi *= math.Sqrt(scaleX * scaleY)
}
return &truetype.Options{
Size: a.PointSize,
DPI: dpi,
Hinting: a.Hinting,
}
}
func (a *FontAttr) newOTOptions(scaleX, scaleY float64) *opentype.FaceOptions {
dpi := a.DPI
if scaleX*scaleY != 0 {
dpi *= math.Sqrt(scaleX * scaleY)
}
return &opentype.FaceOptions{
Size: a.PointSize,
DPI: dpi,
Hinting: a.Hinting,
}
}
func New(name string) (Font, error) {
b, err := os.ReadFile(name)
if err != nil {
return nil, err
}
return NewFromBytes(b)
}
func NewFromBytes(b []byte) (Font, error) {
attr := FontAttr{
PointSize: 12,
DPI: 72,
LineSpacing: 1,
Hinting: font.HintingFull,
}
switch {
case bytes.HasPrefix(b, []byte("STARTFONT")):
font, err := bdf.Parse(b)
if err != nil {
return nil, fmt.Errorf("invalid bitmap data font: %w", err)
}
logrus.Debugf("bdf: %d glyphs with encoding %s", len(font.Characters), font.Encoding)
return &bdfFont{
font: font,
face: font.NewFace().(*bdf.Face),
}, nil
/*
case bytes.HasPrefix(b, []byte{0x00, 0x01, 0x00, 0x00, 0x00}):
font, err := truetype.Parse(b)
if err != nil {
return nil, fmt.Errorf("invalid TrueType font: %w", err)
}
logrus.Debug("ttf")
return &trueTypeFont{
font: font,
face: truetype.NewFace(font, attr.newTTOptions(0, 0)),
}, nil
*/
default:
font, err := opentype.Parse(b)
if err != nil {
return nil, fmt.Errorf("invalid OpenType font: %w", err)
}
logrus.Debugf("otf: %d glyphs %s", font.NumGlyphs(), font)
face, _ := opentype.NewFace(font, attr.newOTOptions(0, 0))
return &openTypeFont{
font: font,
face: face,
attr: attr,
}, nil
}
}
+127
View File
@@ -0,0 +1,127 @@
package font
import (
"image"
"github.com/zachomedia/go-bdf"
"golang.org/x/image/math/fixed"
"github.com/BeatGlow/display/draw"
)
// Bitmap Distribution Format fonts contained.
var (
SM4TIK = Must(NewFromBytes(sm4tikBDF))
Siji = Must(NewFromBytes(sijiBDF))
Spleen5x8 = Must(NewFromBytes(spleen5x8BDF))
Spleen6x12 = Must(NewFromBytes(spleen6x12BDF))
Spleen8x16 = Must(NewFromBytes(spleen8x16BDF))
)
// Icons mapped in SM4TIK
const (
IconAC rune = 0xE000 + iota
IconACAlt
IconArch
IconArchAlt
IconBatEmpty
IconBatEmptyAlt
IconBatFull
IconBatFullAlt
IconBatLow
IconBatLowAlt
IconBluetooth
IconBug
IconBugAlt
IconCat
IconClock
IconCPU
IconDish
IconDiskette
IconEmpty
IconEyeLeft
IconEyeRight
IconFox
IconStar
IconStarAlt
IconFull
IconForward
IconHalf
IconInfo
IconInfoAlt1
IconinfoAlt2
IconMail
IconMemory
IconMouse
IconNetDown
IconNetDownAlt1
IconNetDownAlt2
IconNetUp
IconNetUpAlt1
IconNetUpAlt2
IconNetWired
IconNext
IconNote
IconPacman
IconPause
IconPhones
IconPlay
IconPlug
IconPrev
IconRewind
IconScorpion
IconShroom
IconSpeaker
IconSpeakerAlt1
IconSpeakerAlt2
IconStop
IconTemp
IconTest
IconUSB
IconUSBAlt
IconWiFi
IconWifiAlt
)
type bdfFont struct {
font *bdf.Font
face *bdf.Face
attr FontAttr
}
func (f *bdfFont) MeasureString(s string) (width, height int) {
metrics := f.face.Metrics()
if c, ok := f.font.CharMap[f.font.DefaultChar]; ok {
width = len(s) * c.Advance[0]
} else {
width = len(s) * f.font.Characters[0].Advance[0]
}
height = (metrics.Ascent + metrics.Descent).Ceil()
return
}
func (f *bdfFont) Draw(dst draw.Image, p image.Point, fg image.Image, text string) {
var (
metrics = f.face.Metrics()
dot = fixed.P(p.X, metrics.Ascent.Ceil()+p.Y)
prevC rune = -1
)
for _, c := range text {
if prevC >= 0 {
dot.X += f.face.Kern(prevC, c)
}
dr, mask, maskp, advance, _ := f.face.Glyph(dot, c)
if !dr.Empty() {
draw.DrawMask(dst, dr, fg, image.Point{}, mask, maskp, draw.Over)
}
dot.X += advance
prevC = c
}
}
func (f *bdfFont) SetDPI(_ float64) Font { return f }
func (f *bdfFont) WithDPI(_ float64) Font { return f }
func (f *bdfFont) SetPointSize(_ float64) Font { return f }
func (f *bdfFont) WithPointSize(_ float64) Font { return f }
func (f *bdfFont) SetHinting(_ Hinting) Font { return f }
+150
View File
@@ -0,0 +1,150 @@
package font
import (
"image"
"strings"
"golang.org/x/image/font"
"golang.org/x/image/font/opentype"
"golang.org/x/image/math/fixed"
"github.com/BeatGlow/display/draw"
)
// openTypeFont contains a TrueType or OpenType font face.
type openTypeFont struct {
font *opentype.Font
face font.Face
attr FontAttr
fg, bg image.Image
scaleX, scaleY float64
changed bool
}
func (f openTypeFont) Attr() FontAttr {
return f.attr
}
// SetPointSize sets the point size of the font.
func (f *openTypeFont) SetPointSize(size float64) Font {
if size == f.attr.PointSize {
return f
}
f.attr.PointSize = size
f.changed = true
return f
}
// WithPointSize returns a new font instance with new point size settings.
func (f *openTypeFont) WithPointSize(size float64) Font {
v := new(openTypeFont)
*v = *f
v.SetPointSize(size)
return v
}
// SetDPI sets the resolution of the font in dots per inches (DPI).
func (f *openTypeFont) SetDPI(dpi float64) Font {
if dpi == f.attr.DPI {
return f
}
f.attr.DPI = dpi
f.changed = true
return f
}
// WithDPI returns a new font instance with new DPI settings.
func (f *openTypeFont) WithDPI(dpi float64) Font {
v := new(openTypeFont)
*v = *f
v.SetDPI(dpi)
return v
}
// SetLineSpacing sets the amount of spacing between lines (in terms of font height).
func (f *openTypeFont) SetLineSpacing(spacing float64) {
if spacing == f.attr.LineSpacing {
return
}
f.attr.LineSpacing = spacing
f.changed = true
}
// SetHinting sets the hinting type.
func (f *openTypeFont) SetHinting(hinting Hinting) Font {
if hinting == f.attr.Hinting {
return f
}
f.attr.Hinting = hinting
f.changed = true
return f
}
// SetScale sets the ratio of actual pixel/GL point.
func (f *openTypeFont) SetScaleXY(x, y float64) {
if x == f.scaleX && y == f.scaleY {
return
}
f.scaleX = x
f.scaleY = y
f.changed = true
}
// updateFace updates the font face if parameters have changed.
func (f *openTypeFont) updateFace() {
if f.changed {
f.face, _ = opentype.NewFace(f.font, f.attr.newOTOptions(f.scaleX, f.scaleY))
f.changed = false
}
}
// MeasureText returns the minimum width and height in pixels necessary for an image to contain
// the specified text. The supplied text string can contain line break escape sequences (\n).
func (f *openTypeFont) MeasureString(text string) (width, height int) {
f.updateFace()
bounds, _ := font.BoundString(f.face, text)
width = (bounds.Max.X - bounds.Min.X).Ceil()
metrics := f.face.Metrics()
height = (metrics.Ascent + metrics.Descent).Ceil()
return
}
// Metrics returns the font metrics.
func (f *openTypeFont) Metrics() font.Metrics {
f.updateFace()
return f.face.Metrics()
}
// Draw text onto an image using this font.
func (f *openTypeFont) Draw(dst draw.Image, p image.Point, fg image.Image, text string) {
f.updateFace()
var (
metrics = f.face.Metrics()
py = p.Y + metrics.Ascent.Round()
lineHeight = (metrics.Ascent + metrics.Descent).Ceil()
lineGap = int((f.attr.LineSpacing - float64(1)) * float64(lineHeight))
lines = strings.Split(text, "\n")
drawer = &font.Drawer{
Dst: dst,
Src: fg,
Face: f.face,
}
)
bounds, _ := drawer.BoundString(text)
drawer.Dot = fixed.P(p.X, 1+p.Y)
drawer.Dot = drawer.Dot.Sub(bounds.Min)
for i, line := range lines {
drawer.DrawString(line)
drawer.Dot.Y += fixed.I(py)
py += lineHeight
if i > 1 {
py += lineGap
}
}
}
+150
View File
@@ -0,0 +1,150 @@
package font
import (
"image"
"strings"
"github.com/golang/freetype/truetype"
"golang.org/x/image/font"
"golang.org/x/image/math/fixed"
"github.com/BeatGlow/display/draw"
)
// trueTypeFont contains a TrueType font face.
type trueTypeFont struct {
font *truetype.Font
face font.Face
attr FontAttr
fg, bg image.Image
scaleX, scaleY float64
changed bool
}
func (f trueTypeFont) Attr() FontAttr {
return f.attr
}
// SetPointSize sets the point size of the font.
func (f *trueTypeFont) SetPointSize(size float64) Font {
if size == f.attr.PointSize {
return f
}
f.attr.PointSize = size
f.changed = true
return f
}
// WithPointSize returns a new font instance with new point size settings.
func (f *trueTypeFont) WithPointSize(size float64) Font {
v := new(trueTypeFont)
*v = *f
v.SetPointSize(size)
return v
}
// SetDPI sets the resolution of the font in dots per inches (DPI).
func (f *trueTypeFont) SetDPI(dpi float64) Font {
if dpi == f.attr.DPI {
return f
}
f.attr.DPI = dpi
f.changed = true
return f
}
// WithDPI returns a new font instance with new DPI settings.
func (f *trueTypeFont) WithDPI(dpi float64) Font {
v := new(trueTypeFont)
*v = *f
v.SetDPI(dpi)
return v
}
// SetLineSpacing sets the amount of spacing between lines (in terms of font height).
func (f *trueTypeFont) SetLineSpacing(spacing float64) {
if spacing == f.attr.LineSpacing {
return
}
f.attr.LineSpacing = spacing
f.changed = true
}
// SetHinting sets the hinting type.
func (f *trueTypeFont) SetHinting(hinting Hinting) Font {
if hinting == f.attr.Hinting {
return f
}
f.attr.Hinting = hinting
f.changed = true
return f
}
// SetScale sets the ratio of actual pixel/GL point.
func (f *trueTypeFont) SetScaleXY(x, y float64) {
if x == f.scaleX && y == f.scaleY {
return
}
f.scaleX = x
f.scaleY = y
f.changed = true
}
// updateFace updates the font face if parameters have changed.
func (f *trueTypeFont) updateFace() {
if f.changed {
f.face = truetype.NewFace(f.font, f.attr.newTTOptions(f.scaleX, f.scaleY))
f.changed = false
}
}
// MeasureText returns the minimum width and height in pixels necessary for an image to contain
// the specified text. The supplied text string can contain line break escape sequences (\n).
func (f *trueTypeFont) MeasureString(text string) (width, height int) {
f.updateFace()
bounds, _ := font.BoundString(f.face, text)
width = (bounds.Max.X - bounds.Min.X).Ceil()
metrics := f.face.Metrics()
height = (metrics.Ascent + metrics.Descent).Ceil()
return
}
// Metrics returns the font metrics.
func (f *trueTypeFont) Metrics() font.Metrics {
f.updateFace()
return f.face.Metrics()
}
// Draw text onto an image using this font.
func (f *trueTypeFont) Draw(dst draw.Image, p image.Point, fg image.Image, text string) {
f.updateFace()
var (
metrics = f.face.Metrics()
py = p.Y + metrics.Ascent.Round()
lineHeight = (metrics.Ascent + metrics.Descent).Ceil()
lineGap = int((f.attr.LineSpacing - float64(1)) * float64(lineHeight))
lines = strings.Split(text, "\n")
drawer = &font.Drawer{
Dst: dst,
Src: fg,
Face: f.face,
}
)
bounds, _ := drawer.BoundString(text)
drawer.Dot = fixed.P(p.X, 1+p.Y)
drawer.Dot = drawer.Dot.Sub(bounds.Min)
for i, line := range lines {
drawer.DrawString(line)
drawer.Dot.Y += fixed.I(py)
py += lineHeight
if i > 1 {
py += lineGap
}
}
}
+10412
View File
File diff suppressed because it is too large. Load diff
File renamed without changes.
File renamed without changes.
File renamed without changes.
+50
View File
@@ -1,11 +1,18 @@
package app
import (
"bytes"
"image"
"image/color"
"image/draw"
"github.com/sirupsen/logrus"
"github.com/BeatGlow/display/pixel"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
)
// BufferFor creates a new image buffer for the provided display matching its color model.
@@ -32,11 +39,13 @@ type clearer interface {
// ImageCopy copies an image over dst.
func ImageCopy(dst draw.Image, src image.Image) {
logrus.Tracef("image copy %s -> %s", src.Bounds(), dst.Bounds())
draw.Draw(dst, dst.Bounds(), src, image.Point{}, draw.Src)
}
// ImageCopyBounds copies an image over dst bounded by r.
func ImageCopyBounds(dst draw.Image, src image.Image, r image.Rectangle) {
logrus.Tracef("image copy %s -> %s (of %s)", src.Bounds(), r, dst.Bounds())
draw.Draw(dst, r, src, image.Point{}, draw.Src)
}
@@ -74,3 +83,44 @@ func ImageFill(dst draw.Image, c color.Color) {
draw.Draw(dst, dst.Bounds(), src, image.Point{}, draw.Src)
}
// MustDecodeImage can decode JPEG, GIF and PNG images.
func MustDecodeImage(b []byte) image.Image {
i, _, err := image.Decode(bytes.NewBuffer(b))
if err != nil {
panic(err)
}
return i
}
type HorizontalWrappingImage struct {
image.Image
Gap int
}
func (i HorizontalWrappingImage) At(x, y int) color.Color {
var (
bounds = i.Image.Bounds()
dx = (bounds.Max.X - bounds.Min.X)
ox = x
oy = y
)
for ox < bounds.Min.X {
ox += dx
}
for ox >= bounds.Max.X {
ox -= dx
}
return i.Image.At(ox, oy)
}
func (i HorizontalWrappingImage) Bounds() image.Rectangle {
var (
bounds = i.Image.Bounds()
delta = image.Point{X: (bounds.Max.X - bounds.Min.X) + i.Gap}
)
return image.Rectangle{
Min: bounds.Min.Sub(delta),
Max: bounds.Max.Add(delta),
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

+72
View File
@@ -0,0 +1,72 @@
package layout
import (
"github.com/sirupsen/logrus"
"github.com/BeatGlow/beatglow/app"
)
type base struct {
name string
widgets []app.Widget
visible bool
onButtonPress func(app.Context)
onButtonLongPress func(app.Context)
}
func (l *base) log() *logrus.Entry {
return logrus.WithField("layout", l.name)
}
func (l *base) String() string {
return l.name
}
func (l *base) Widgets() []app.Widget {
return l.widgets
}
func (l *base) IsVisible() bool {
return l.visible
}
func (l *base) Hide(ctx app.Context) {
log := l.log()
log.Debug("hide")
for _, widget := range l.widgets {
log.WithField("widget", widget.String()).Debug("hide widget")
_ = widget.Hide(ctx)
}
l.visible = false
}
func (l *base) Show(ctx app.Context) {
log := l.log()
log.Debug("show")
ctx.Display().Clear()
for _, widget := range l.widgets {
log.WithField("widget", widget.String()).Debug("show widget")
_ = widget.Show(ctx)
}
l.visible = true
}
func (i *base) OnButtonPress(action func(app.Context)) {
i.onButtonPress = action
}
func (i *base) OnButtonLongPress(action func(app.Context)) {
i.onButtonLongPress = action
}
func (l *base) HandleButtonPress(ctx app.Context) {
if l.onButtonPress != nil {
l.onButtonPress(ctx)
}
}
func (l *base) HandleButtonLongPress(ctx app.Context) {
if l.onButtonLongPress != nil {
l.onButtonLongPress(ctx)
}
}
+228 -25
View File
@@ -3,85 +3,288 @@ package layout
import (
"fmt"
"image"
"image/color"
"strings"
"time"
"github.com/sirupsen/logrus"
"periph.io/x/conn/v3/physic"
"github.com/BeatGlow/audio"
"github.com/BeatGlow/beatglow/app"
"github.com/BeatGlow/beatglow/app/font"
"github.com/BeatGlow/beatglow/app/widget"
"github.com/BeatGlow/beatglow/player"
_ "embed"
)
const (
formatTextPlaceholder = "None"
// "FLAC@192k "
// "FLAC@44.1k"
formatTextPlaceholder = "No track "
durationTextPlaceholder = "--:-- / --:--"
trackTextPlaceholder = "No track playing..."
trackTextPlaceholder = "No track playing"
iconTextPlaceholder = string(font.IconPhones)
)
type playing struct {
base
phonesWidget *widget.Text
formatRate bool
formatText string
formatWidget *widget.Text
durationText string
durationWidget *widget.Text
track *player.Track
trackText string
trackWidget *widget.Text
iconText string
iconWidget *widget.Text
artWidget *widget.Image
spectrumWidget *widget.Spectrum
}
const playingWaterfallHeight = 32
func Playing(ctx app.Context) app.Layout {
bounds := ctx.Display().Bounds()
styles := app.StylesFor(ctx)
layout := &playing{
base: base{name: "playing"},
phonesWidget: widget.NewText(image.Pt(10, 12)),
formatText: formatTextPlaceholder,
formatWidget: widget.NewText(image.Pt(2+len(formatTextPlaceholder)*8, 12)),
formatWidget: widget.NewText(image.Pt(2+len(formatTextPlaceholder)*9, 12)),
durationText: durationTextPlaceholder,
durationWidget: widget.NewText(image.Pt(2+len(durationTextPlaceholder)*8, 12)),
durationWidget: widget.NewText(image.Pt(2+len(durationTextPlaceholder)*9, 12)),
trackText: trackTextPlaceholder,
trackWidget: widget.NewText(image.Pt(bounds.Dx()-bounds.Dy(), bounds.Dy()-12-16)),
trackWidget: widget.NewText(image.Pt(bounds.Dx()-bounds.Dy(), bounds.Dy()-12-playingWaterfallHeight)),
iconText: iconTextPlaceholder,
iconWidget: widget.NewText(image.Pt(10, 12)),
artWidget: widget.NewImage(image.Pt(bounds.Dy(), bounds.Dy())),
spectrumWidget: widget.NewSpectrum(image.Pt(bounds.Dx()-bounds.Dy(), playingWaterfallHeight)),
}
var (
formatStyle = styles.Text.WithFont(font.Spleen6x12)
iconStyle = styles.Text.WithFont(font.SM4TIK).WithForegroundColor(color.Gray{0x3f})
durationStyle = formatStyle
titleStyle = styles.Text.WithFont(font.Montserrat.WithPointSize(20))
offset int
)
layout.phonesWidget.
SetStyle(iconStyle).
Update(string(font.IconNote)).
Resize(measureString(iconStyle.Font, iconTextPlaceholder)).
Move(image.Pt(offset, -3))
offset += 10
layout.formatWidget.
SetStyle(formatStyle).
Bind(&layout.formatText).
Move(image.Pt(0, 0))
Resize(measureString(formatStyle.Font, formatTextPlaceholder)).
Move(image.Pt(offset, 0))
offset += layout.formatWidget.Bounds().Dx() + 10
layout.iconWidget.
SetStyle(iconStyle).
Bind(&layout.iconText).
Resize(measureString(iconStyle.Font, iconTextPlaceholder)).
Move(image.Pt(offset, -3))
offset += 10
layout.durationWidget.
SetStyle(durationStyle).
Bind(&layout.durationText).
Move(layout.formatWidget.Bounds().Min.Add(image.Pt(8, 0)))
Resize(measureString(formatStyle.Font, durationTextPlaceholder)).
Move(image.Pt(offset, 0))
layout.trackWidget.
SetStyle(titleStyle).
SetScroll(1, 8, time.Second/20).
Bind(&layout.trackText).
Move(image.Pt(0, 12))
layout.artWidget.
Move(image.Pt(bounds.Dx()-bounds.Dy(), 0))
layout.spectrumWidget.
SetWaterfall(false).
SetChannels(2).
SetStyles(*styles).
Move(image.Pt(0, bounds.Dy()-playingWaterfallHeight))
layout.widgets = []app.Widget{
layout.phonesWidget,
layout.formatWidget,
layout.iconWidget,
layout.durationWidget,
layout.trackWidget,
layout.artWidget,
layout.spectrumWidget,
}
return layout
}
/*
func (l *playing) log() *logrus.Entry {
return logrus.WithField("layout", "playing")
}
func (playing) String() string {
return "playing"
}
func (layout *playing) Widgets() []app.Widget {
return []app.Widget{
layout.formatWidget,
layout.durationWidget,
layout.trackWidget,
layout.artWidget,
func (l *playing) Hide(ctx app.Context) {
log := l.log()
log.Debug("hide")
for _, widget := range l.Widgets() {
log.WithField("widget", widget.String()).Debug("hide widget")
_ = widget.Hide(ctx)
}
}
func (layout *playing) TrackChanged(track *player.Track) {
if track == nil {
layout.formatText = formatTextPlaceholder
layout.durationText = durationTextPlaceholder
layout.trackText = trackTextPlaceholder
} else {
layout.trackText = track.Artist + " - " + track.Title
layout.formatText = strings.ToUpper(track.Format)
layout.durationText = fmt.Sprintf("00:00 / %s", formatDuration(track.Duration))
func (l *playing) Show(ctx app.Context) {
log := l.log()
log.Debug("show")
for _, widget := range l.Widgets() {
log.WithField("widget", widget.String()).Debug("show widget")
_ = widget.Show(ctx)
}
}
func (l *playing) Widgets() []app.Widget {
return []app.Widget{
l.phonesWidget,
l.formatWidget,
l.iconWidget,
l.durationWidget,
l.trackWidget,
l.artWidget,
l.spectrumWidget,
}
}
*/
func (l *playing) TrackChanged(ctx app.Context, track *player.Track) {
if track == nil {
l.formatText = formatTextPlaceholder
l.durationText = durationTextPlaceholder
l.trackText = trackTextPlaceholder
} else {
l.trackText = formatTrack(track)
l.formatRate = false
l.formatText = strings.ToUpper(track.Format)
}
if !track.Eq(l.track) {
l.track = track
l.artWidget.Update(beatglowLogo, ctx.Display().ColorModel())
go l.updateArt(ctx, track)
}
}
func (l *playing) updateArt(ctx app.Context, track *player.Track) {
log := logrus.WithField("track", track)
if fetcher, ok := ctx.Player().(player.AlbumArt); ok {
if image, ok := fetcher.AlbumArt(track); ok {
log.WithField("size", image.Bounds().Size()).Debug("updating album art")
l.artWidget.Update(image, ctx.Display().ColorModel())
return
}
}
log.Debug("updating album art failed: unavailable")
}
func (l *playing) StatusChanged(ctx app.Context, status *player.Status) {
if status == nil {
l.formatText = formatTextPlaceholder
l.durationText = durationTextPlaceholder
l.trackText = trackTextPlaceholder
l.iconText = string(font.IconBug)
return
}
if status.Paused {
l.iconText = string(font.IconPause)
} else if status.Playing {
l.iconText = string(font.IconPlay)
} else {
l.iconText = string(font.IconStop)
}
if status.Duration > 0 {
l.durationText = fmt.Sprintf("%s / %s", formatDuration(status.Elapsed), formatDuration(status.Duration))
}
if status.Track != nil {
if l.formatRate {
l.formatText = fmt.Sprintf("%04d@%s", status.Format.BitRate, formatRate(status.Format.SampleRate))
} else {
l.formatText = fmt.Sprintf("%-4s@%s", strings.ToUpper(status.Track.Format), formatRate(status.Format.SampleRate))
}
l.formatRate = !l.formatRate
}
}
func (l *playing) ProcessBuffer(buffer audio.Buffer[float64]) {
if l.spectrumWidget.IsVisible() {
l.spectrumWidget.ProcessBuffer(buffer)
}
}
func measureString(font font.Font, text string) image.Point {
width, height := font.MeasureString(text)
return image.Pt(width, height)
}
func formatDuration(d time.Duration) string {
h := int(d / time.Hour)
d -= time.Duration(h) * time.Hour
m := int(d / time.Minute)
return fmt.Sprintf("%02d:%02d", h, m)
d -= time.Duration(m) * time.Minute
s := int(d / time.Second)
return fmt.Sprintf("%02d:%02d", m, s)
}
func formatTrack(track *player.Track) string {
var artist, title string
if artist = track.Artist; artist == "" {
artist = "Unknown Artist"
}
if title = track.Title; title == "" {
title = "Unknown Title"
}
return artist + " - " + title
}
func formatRate(rate physic.Frequency) string {
if rate > physic.MegaHertz {
m := rate / physic.MegaHertz
k := (rate - m*physic.MegaHertz) / 100
if m > 100 {
return fmt.Sprintf("%dm", int(m))
}
return fmt.Sprintf("%d.%1dm", int(m), int(k))
} else if rate > physic.KiloHertz {
v := float64(rate) / float64(physic.KiloHertz)
if v >= 100 {
return fmt.Sprintf("%dk", int(v))
}
return fmt.Sprintf("%03.1fk", v)
}
return fmt.Sprintf("%dh", rate/physic.Hertz)
}
var (
_ app.StatusChangeHandler = (*playing)(nil)
_ app.TrackChangeHandler = (*playing)(nil)
_ app.BufferProcessor = (*playing)(nil)
//go:embed asset/beatglow.png
beatglowPNG []byte
beatglowLogo = app.MustDecodeImage(beatglowPNG)
)
+230
View File
@@ -0,0 +1,230 @@
package layout
import (
"reflect"
"strings"
"github.com/BeatGlow/beatglow/app"
"github.com/BeatGlow/beatglow/app/widget"
"github.com/BeatGlow/beatglow/config"
)
type settings struct {
base
settings *config.Settings
menu []settingsMenu
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)
layout := &settings{
base: base{name: "settings"},
menuWidget: widget.NewMenu(bounds.Size()),
settings: ctx.Settings(),
}
layout.menuWidget.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")
}
}
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")
ctx.Show(nil)
}
return
}
log.Debug("handle selected item")
l.handleSelect(l.index - 1)
}
}
func (l *settings) HandleButtonLongPress(ctx app.Context) {
if l.menuWidget.IsVisible() {
l.menu = nil
l.show(l.settings)
ctx.Show(nil) // Close settings
}
}
func foreachStructField(v reflect.Value, f func(fv reflect.Value, sf reflect.StructField) (stop bool)) {
t := v.Type()
for i, l := 0, t.NumField(); i < l; i++ {
sf := t.Field(i)
fv := v.Field(i).Addr()
if f(fv, sf) {
break
}
}
}
var (
_ app.RotaryInputHandler = (*settings)(nil)
_ app.ButtonInputHandler = (*settings)(nil)
)
+264
View File
@@ -0,0 +1,264 @@
package menu
import (
"fmt"
"math"
"reflect"
"strconv"
"strings"
)
type Menu struct {
Items []Item
// 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
}
func New(data any, pageSize int, parent *Menu) (*Menu, error) {
ref := reflect.ValueOf(data)
// if its a pointer, resolve its value
if ref.Kind() == reflect.Ptr {
ref = reflect.Indirect(ref)
}
if ref.Kind() == reflect.Interface {
ref = ref.Elem()
}
if ref.Kind() != reflect.Struct {
return nil, fmt.Errorf("menu: %T is not a struct", data)
}
menu := &Menu{
PageSize: pageSize,
Parent: parent,
}
typ := ref.Type()
for i, n := 0, ref.NumField(); i < n; i++ {
var (
field = typ.Field(i)
fieldRef = ref.Field(i)
value = ref.Field(i).Interface()
icon = field.Tag.Get("icon")
label = field.Tag.Get("menu")
options = strings.Split(field.Tag.Get("options"), ",")
step = 1
min, max int
err error
)
if len(label) == 0 {
label = field.Name
} else if label == "-" {
continue
}
if stepTag := field.Tag.Get("step"); stepTag != "" {
if step, err = strconv.Atoi(stepTag); err != nil {
return nil, fmt.Errorf("menu: invalid `step` setting on field %s: %w", field.Name, err)
}
}
if minTag := field.Tag.Get("min"); minTag != "" {
if min, err = strconv.Atoi(minTag); err != nil {
return nil, fmt.Errorf("menu: invalid `min` setting on field %s: %w", field.Name, err)
}
}
if maxTag := field.Tag.Get("max"); maxTag != "" {
if max, err = strconv.Atoi(maxTag); err != nil {
return nil, fmt.Errorf("menu: invalid `max` setting on field %s: %w", field.Name, err)
}
}
switch field.Type.Kind() {
case reflect.Struct:
subMenu, err := New(value, pageSize, menu)
if err != nil {
return nil, err
}
menu.Items = append(menu.Items, Item{
Label: label,
Value: nil,
Field: fieldRef,
Icon: icon,
SubMenu: subMenu,
})
case reflect.Bool, reflect.String:
menu.Items = append(menu.Items, Item{
Label: label,
Value: value,
Field: fieldRef,
Icon: icon,
Options: options,
})
case reflect.Uint8:
if min < 0 || min > math.MaxUint8 || max < 0 || max > math.MaxUint8 {
return nil, fmt.Errorf("menu: min/max %d/%d on field %s.%s is out of range for uint8", min, max, typ.Name(), field.Name)
}
if max == 0 {
max = math.MaxUint8
}
menu.Items = append(menu.Items, Item{
Label: label,
Value: value,
Field: fieldRef,
Icon: icon,
Min: min,
Max: max,
Step: step,
})
case reflect.Int8:
if min < math.MinInt8 || min > math.MaxInt8 || max < math.MinInt8 || max > math.MaxInt8 {
return nil, fmt.Errorf("menu: min/max %d/%d on field %s.%s is out of range for int8", min, max, typ.Name(), field.Name)
}
if min == 0 && max == 0 {
min, max = math.MinInt8, math.MaxInt8
}
if min == max {
return nil, fmt.Errorf("menu: no min/max range specified on field %s.%s", typ.Name(), field.Name)
}
menu.Items = append(menu.Items, Item{
Label: label,
Value: value,
Field: fieldRef,
Icon: icon,
Min: min,
Max: max,
Step: step,
})
case reflect.Int:
if min == max {
return nil, fmt.Errorf("menu: no min/max range specified for field %s.%s", typ.Name(), field.Name)
}
menu.Items = append(menu.Items, Item{
Label: label,
Value: value,
Field: fieldRef,
Icon: icon,
Min: min,
Max: max,
Step: step,
})
default:
return nil, fmt.Errorf("menu: can't render field %s.%s with type %s", typ.Name(), field.Name, field.Type.Kind())
}
}
return menu, nil
}
// Change is used for editing and navigating, delta is either positive or negative input.
func (m *Menu) Change(delta int) {
if m.IsEditing {
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]
switch v := item.Value.(type) {
case int:
newValue := v + delta
if newValue >= item.Min && newValue <= item.Max {
item.Value = newValue
item.Field.SetInt(int64(newValue)) // Update the original struct field
}
case bool:
if delta != 0 {
item.Value = !v
item.Field.SetBool(!v) // Update the original struct field
}
case string:
if len(item.Options) > 0 {
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
}
}
}
}
func (m *Menu) move(delta int) {
// Move the cursor if not editing
m.Position += delta
if m.Position < 0 {
m.Position = 0
} else if m.Position >= len(m.Items) {
m.Position = len(m.Items) - 1
}
}
type Item struct {
// Label on the menu.
Label string
// Icon on the menu.
Icon string
// Value is the original value.
Value interface{}
// Field is the original struct field.
Field reflect.Value
// SubMenu is the submenu item.
SubMenu *Menu
// Min, Max and Step provides the bounds for integers.
Min, Max, Step int
// Options for string values.
Options []string
}
// indexOf returns the index of a value in a slice, or -1 if not found
func indexOf(needle string, haystack []string) int {
for i, opt := range haystack {
if opt == needle {
return i
}
}
return -1
}
+58
View File
@@ -0,0 +1,58 @@
package menu
import "testing"
// Example usage
type testDisplaySettings struct {
Brightness uint8 `icon:"☀️" menu:"Brightness"`
Contrast uint8 `icon:"🔆" menu:"Contrast level" step:"8"`
}
type testAudioSettings struct {
Volume uint8 `icon:"🔊" menu:"Volume" min:"1" max:"100"`
Mute bool `icon:"🔇" menu:"Mute"`
}
type testSpectrumSettings struct {
Waterfall bool `menu:"Waterfall display"`
Stereo bool `menu:"Use stereo channels"`
MinFrequency int `menu:"High pass frequency" min:"0" max:"22050" step:"50"`
MaxFrequency int `menu:"Low pass frequency" min:"0" max:"22050" step:"50"`
}
type testSettings struct {
Display testDisplaySettings `icon:"🖥️" menu:"Display"`
Audio testAudioSettings `icon:"🎧" menu:"Audio"`
Language string `icon:"🌐" menu:"Language"`
Spectrum testSpectrumSettings `menu:"Spectrum analyzer"`
Ignored float64 `menu:"-"`
}
func TestMenu(t *testing.T) {
var settings testSettings
menu, err := New(&settings, 4, nil)
if err != nil {
t.Error(err)
}
t.Logf("menu: %#+v", menu)
}
func TestMenuNil(t *testing.T) {
_, err := New(nil, 4, nil)
if err == nil {
t.Fatal("expected error")
return
}
t.Logf("expected error from nil, got %q", err)
}
func TestMenuNotPointer(t *testing.T) {
var settings testSettings
menu, err := New(settings, 4, nil)
if err != nil {
t.Error(err)
}
t.Logf("menu: %#+v", menu)
}
+468
View File
@@ -0,0 +1,468 @@
package shader
import "math"
// Effect defines the interface for shader effects.
type Effect interface {
Apply(x, y, width, height int, samples []float64) (r, g, b float64)
}
type AudioIntensityBarsEffect struct{}
func (e *AudioIntensityBarsEffect) Apply(x, y, width, height int, sample []float64) (r, g, b float64) {
// Calculate the average amplitude across all channels
amplitude := 0.0
for _, sample := range sample {
amplitude += math.Abs(sample)
}
amplitude /= float64(len(sample))
// Map the amplitude to bar height
barHeight := int(amplitude * float64(height))
// If the current y is within the bar height, light up the pixel
if y < barHeight {
intensity := 1.0 - (float64(y) / float64(barHeight))
r = intensity
g = intensity
b = intensity
}
return r, g, b
}
type StereoColorGradientEffect struct{}
func (e *StereoColorGradientEffect) Apply(x, y, _, _ int, sample []float64) (r, g, b float64) {
left := math.Abs(sample[0])
right := math.Abs(sample[1])
r = left
g = right
b = (left + right) / 2.0
return r, g, b
}
type StereoRippleEffect struct{}
func (e *StereoRippleEffect) Apply(x, y, width, height int, sample []float64) (r, g, b float64) {
centerX := width / 2
centerY := height / 2
dx := float64(x - centerX)
dy := float64(y - centerY)
distance := math.Sqrt(dx*dx + dy*dy)
// Use the difference between left and right channels for ripple intensity
ripple := math.Sin(distance*0.1 - (sample[0]-sample[1])*10.0)
ripple = (ripple + 1.0) / 2.0 // Normalize to [0, 1]
r = ripple
g = ripple * 0.5
b = ripple * 0.2
return r, g, b
}
type StereoSpectrumBarsEffect struct{}
func (e *StereoSpectrumBarsEffect) Apply(x, y, width, height int, sample []float64) (r, g, b float64) {
barWidth := 10
barIndex := x / barWidth
// Use left channel for even bars, right channel for odd bars
var amplitude float64
if barIndex%2 == 0 {
amplitude = math.Abs(sample[0])
} else {
amplitude = math.Abs(sample[1])
}
barHeight := int(amplitude * float64(barWidth))
if y < barHeight {
r = 1.0
g = 0.5
b = 0.0
}
return r, g, b
}
type ChannelSeparationEffect struct {
}
func (e *ChannelSeparationEffect) Apply(x, y, width, _ int, sample []float64) (r, g, b float64) {
// Split the screen vertically for stereo separation
if len(sample) > 1 {
if x < width/2 {
// Left channel controls the left side
r = math.Abs(sample[0])
g = 0.0
b = 0.0
} else {
// Right channel controls the right side
r = 0.0
g = math.Abs(sample[1])
b = 0.0
}
} else {
// Mono audio: use the same value for both sides
r = math.Abs(sample[0])
g = math.Abs(sample[0])
b = math.Abs(sample[0])
}
return r, g, b
}
type StereoWaveformEffect struct{}
func (e *StereoWaveformEffect) Apply(x, y, _, _ int, sample []float64) (r, g, b float64) {
// Map the audio sample to the y-axis for each channel
if len(sample) > 1 {
leftY := int((sample[0] + 1.0) / 2.0 * float64(64))
rightY := int((sample[1] + 1.0) / 2.0 * float64(64))
// Left channel (red)
if math.Abs(float64(y)-float64(leftY)) < 2 {
r = 1.0
}
// Right channel (green)
if math.Abs(float64(y)-float64(rightY)) < 2 {
g = 1.0
}
} else {
// Mono audio: single waveform
waveY := int((sample[0] + 1.0) / 2.0 * float64(64))
if math.Abs(float64(y)-float64(waveY)) < 2 {
r = 1.0
g = 1.0
b = 1.0
}
}
return r, g, b
}
type StereoSpectrumEffect struct {
BarHeight int
}
func (e *StereoSpectrumEffect) Apply(x, y, _, _ int, sample []float64) (r, g, b float64) {
// Divide the screen into horizontal bars for each channel
barHeight := e.BarHeight
if barHeight < 1 {
barHeight = 8
}
barIndex := y / barHeight
if len(sample) > 1 {
if barIndex%2 == 0 {
// Left channel (red)
r = math.Abs(sample[0])
} else {
// Right channel (green)
g = math.Abs(sample[1])
}
} else {
// Mono audio: use the same value for all bars
r = math.Abs(sample[0])
g = math.Abs(sample[0])
b = math.Abs(sample[0])
}
return r, g, b
}
type StereoRadialEffect struct {
}
func (e *StereoRadialEffect) Apply(x, y, width, height int, sample []float64) (r, g, b float64) {
// Center of the screen
centerX := width / 2
centerY := height / 2
// Distance and angle from the center
dx := float64(x - centerX)
dy := float64(y - centerY)
distance := math.Sqrt(dx*dx + dy*dy)
angle := math.Atan2(dy, dx)
if len(sample) > 1 {
// Left channel controls the top half, right channel controls the bottom half
if angle > 0 {
r = math.Abs(sample[0]) * (1.0 - distance/128.0)
} else {
g = math.Abs(sample[1]) * (1.0 - distance/128.0)
}
} else {
// Mono audio: uniform radial effect
r = math.Abs(sample[0]) * (1.0 - distance/128.0)
g = math.Abs(sample[0]) * (1.0 - distance/128.0)
b = math.Abs(sample[0]) * (1.0 - distance/128.0)
}
return r, g, b
}
type StereoPulseEffect struct{}
func (e *StereoPulseEffect) Apply(x, y, _, _ int, sample []float64) (r, g, b float64) {
if len(sample) > 1 {
// Left channel controls horizontal pulsation
r = 0.5 + 0.5*math.Sin(float64(x)*0.1+sample[0]*10.0)
// Right channel controls vertical pulsation
g = 0.5 + 0.5*math.Sin(float64(y)*0.1+sample[1]*10.0)
} else {
// Mono audio: uniform pulsation
pulse := 0.5 + 0.5*math.Sin(float64(x+y)*0.1+sample[0]*10.0)
r = pulse
g = pulse
b = pulse
}
return r, g, b
}
type StereoSwirlEffect struct {
}
func (e *StereoSwirlEffect) Apply(x, y, width, height int, sample []float64) (r, g, b float64) {
// Center of the screen
centerX := width / 2
centerY := height / 2
// Distance and angle from the center
dx := float64(x - centerX)
dy := float64(y - centerY)
angle := math.Atan2(dy, dx)
if len(sample) > 1 {
// Left channel controls clockwise swirl, right channel controls counterclockwise swirl
swirl := math.Sin(angle+sample[0]*10.0) + math.Cos(angle-sample[1]*10.0)
r = (swirl + 1.0) / 2.0
g = (1.0 - swirl) / 2.0
b = 0.5
} else {
// Mono audio: uniform swirl
swirl := math.Sin(angle + sample[0]*10.0)
r = (swirl + 1.0) / 2.0
g = (1.0 - swirl) / 2.0
b = 0.5
}
return r, g, b
}
type StereoMirrorEffect struct {
Width int
}
func (e *StereoMirrorEffect) Apply(x, y, _, _ int, sample []float64) (r, g, b float64) {
if len(sample) > 1 {
if x < e.Width/2 {
// Left channel controls the left side
r = math.Abs(sample[0])
} else {
// Right channel controls the mirrored right side
r = math.Abs(sample[1])
}
} else {
// Mono audio: uniform mirror
r = math.Abs(sample[0])
}
g = r
b = r
return r, g, b
}
type PulsatingCirclesEffect struct {
}
func (e *PulsatingCirclesEffect) Apply(x, y, width, height int, sample []float64) (r, g, b float64) {
// Center of the screen
centerX := width / 2
centerY := height / 2
// Distance from the center
dx := float64(x - centerX)
dy := float64(y - centerY)
distance := math.Sqrt(dx*dx + dy*dy)
// Calculate the average amplitude across all channels
amplitude := 0.0
for _, sample := range sample {
amplitude += math.Abs(sample)
}
amplitude /= float64(len(sample))
// Map the amplitude to the circle radius
radius := amplitude * 64.0
// Light up pixels near the circle boundary
if math.Abs(distance-radius) < 2 {
intensity := 1.0
r = intensity
g = intensity
b = intensity
}
return r, g, b
}
type AudioNoiseEffect struct{}
func (e *AudioNoiseEffect) Apply(x, y, _, _ int, sample []float64) (r, g, b float64) {
// Calculate the average amplitude across all channels
amplitude := 0.0
for _, sample := range sample {
amplitude += math.Abs(sample)
}
amplitude /= float64(len(sample))
// Generate noise based on the amplitude
noise := math.Sin(float64(x*y)) * amplitude
intensity := (noise + 1.0) / 2.0
r = intensity
g = intensity
b = intensity
return r, g, b
}
type AudioRipplesEffect struct{}
func (e *AudioRipplesEffect) Apply(x, y, width, height int, sample []float64) (r, g, b float64) {
// Center of the screen
centerX := width / 2
centerY := height / 2
// Distance from the center
dx := float64(x - centerX)
dy := float64(y - centerY)
distance := math.Sqrt(dx*dx + dy*dy)
// Calculate the average amplitude across all channels
amplitude := 0.0
for _, sample := range sample {
amplitude += math.Abs(sample)
}
amplitude /= float64(len(sample))
// Create ripples based on the amplitude
ripple := math.Sin(distance*0.1 - amplitude*10.0)
intensity := (ripple + 1.0) / 2.0
r = intensity
g = intensity
b = intensity
return r, g, b
}
type AudioScanlinesEffect struct{}
func (e *AudioScanlinesEffect) Apply(x, y, _, _ int, sample []float64) (r, g, b float64) {
// Calculate the average amplitude across all channels
amplitude := 0.0
for _, sample := range sample {
amplitude += math.Abs(sample)
}
amplitude /= float64(len(sample))
// Alternate scanlines based on the amplitude
if y%2 == 0 {
intensity := amplitude
r = intensity
g = intensity
b = intensity
} else {
intensity := 1.0 - amplitude
r = intensity
g = intensity
b = intensity
}
return r, g, b
}
type MoireRotatingZoomerEffect struct {
Time float64 // Time counter for animation
}
func (e *MoireRotatingZoomerEffect) Apply(x, y, width, height int, sample []float64) (r, g, b float64) {
// Center of the screen
centerX := float64(width) / 2.0
centerY := float64(height) / 2.0
// Normalized coordinates relative to the center
dx := float64(x) - centerX
dy := float64(y) - centerY
// Calculate the average amplitude across all channels
amplitude := 0.0
for _, sample := range sample {
amplitude += math.Abs(sample)
}
amplitude /= float64(len(sample))
// Use amplitude to modulate rotation speed and zoom level
rotationSpeed := 0.5 + amplitude*2.0 // Speed increases with amplitude
zoomLevel := 1.0 + amplitude*2.0 // Zoom increases with amplitude
// Update time for animation
e.Time += 0.01 * rotationSpeed
// Rotate and zoom the coordinates
angle := e.Time
cosA := math.Cos(angle)
sinA := math.Sin(angle)
rotatedX := dx*cosA - dy*sinA
rotatedY := dx*sinA + dy*cosA
// Apply zoom
rotatedX /= zoomLevel
rotatedY /= zoomLevel
// Create a Moiré pattern using sine waves
moire := math.Sin(rotatedX*0.1) * math.Sin(rotatedY*0.1)
// Map the Moiré pattern to gray scale intensity
intensity := (moire + 1.0) / 2.0 // Normalize to [0, 1]
r = intensity
g = intensity
b = intensity
return r, g, b
}
type RadialAudioIntensityEffect struct{}
func (e *RadialAudioIntensityEffect) Apply(x, y, width, height int, audioSample []float64) (r, g, b float64) {
// Center of the screen
centerX := float64(width) / 2.0
centerY := float64(height) / 2.0
// Distance from the center
dx := float64(x) - centerX
dy := float64(y) - centerY
distance := math.Sqrt(dx*dx + dy*dy)
// Calculate the average amplitude across all channels
amplitude := 0.0
for _, sample := range audioSample {
amplitude += math.Abs(sample)
}
amplitude /= float64(len(audioSample))
// Map the amplitude to the radial intensity
intensity := amplitude * (1.0 - distance/float64(width/2))
r = intensity
g = intensity
b = intensity
return r, g, b
}
var (
_ Effect = (*AudioIntensityBarsEffect)(nil)
_ Effect = (*AudioNoiseEffect)(nil)
_ Effect = (*AudioRipplesEffect)(nil)
_ Effect = (*AudioScanlinesEffect)(nil)
_ Effect = (*MoireRotatingZoomerEffect)(nil)
_ Effect = (*PulsatingCirclesEffect)(nil)
_ Effect = (*RadialAudioIntensityEffect)(nil)
_ Effect = (*StereoColorGradientEffect)(nil)
_ Effect = (*StereoMirrorEffect)(nil)
_ Effect = (*StereoPulseEffect)(nil)
_ Effect = (*StereoRadialEffect)(nil)
_ Effect = (*StereoSpectrumBarsEffect)(nil)
_ Effect = (*StereoSwirlEffect)(nil)
_ Effect = (*StereoWaveformEffect)(nil)
)
+89
View File
@@ -0,0 +1,89 @@
package shader
import (
"image"
"image/color"
"image/draw"
"math"
"github.com/BeatGlow/audio"
"github.com/BeatGlow/display/pixel"
)
// Shader represents a shader that can render effects based on an audio stream.
type Shader struct {
Effects []Effect // List of effects to apply
canvas draw.Image
buffer audio.Buffer[float64]
}
func New(model color.Model, size image.Point) *Shader {
switch model {
case pixel.MonoModel:
return &Shader{canvas: pixel.NewMonoImage(size.X, size.Y)}
case pixel.Gray2Model:
return &Shader{canvas: pixel.NewGray2Image(size.X, size.Y)}
case pixel.Gray4Model:
return &Shader{canvas: pixel.NewGray4Image(size.X, size.Y)}
default:
return &Shader{canvas: image.NewRGBA(image.Rectangle{Max: size})}
}
}
func (s *Shader) ProcessBuffer(buffer audio.Buffer[float64]) {
if s.buffer == nil {
s.buffer = make(audio.Buffer[float64], len(buffer))
for channel, channels := 0, len(s.buffer); channel < channels; channel++ {
s.buffer[channel] = make([]float64, len(buffer[0]))
}
}
for channel, channels := 0, len(s.buffer); channel < channels; channel++ {
copy(s.buffer[channel], buffer[channel])
}
}
func (s *Shader) Render() image.Image {
size := s.canvas.Bounds().Size()
for y := 0; y < size.Y; y++ {
for x := 0; x < size.X; x++ {
// Calculate the index in the audio data based on the x position
audioIndex := int(float64(x) / float64(size.X) * float64(len(s.buffer[0])))
if audioIndex >= len(s.buffer[0]) {
audioIndex = len(s.buffer[0]) - 1
}
// Get the audio sample for all channels
audioSample := make([]float64, len(s.buffer))
for channel := range s.buffer {
audioSample[channel] = s.buffer[channel][audioIndex]
}
// Apply all effects
r, g, b := 0.0, 0.0, 0.0
for _, fx := range s.Effects {
er, eg, eb := fx.Apply(x, y, size.X, size.Y, audioSample)
r += er
g += eg
b += eb
}
// Normalize the color values to the range [0, 1]
r = math.Min(math.Max(r, 0.0), 1.0)
g = math.Min(math.Max(g, 0.0), 1.0)
b = math.Min(math.Max(b, 0.0), 1.0)
// Set the pixel color
s.canvas.Set(x, y, color.RGBA{
R: uint8(r * 255),
G: uint8(g * 255),
B: uint8(b * 255),
A: 255,
})
}
}
return s.canvas
}
+51 -10
View File
@@ -5,8 +5,9 @@ import (
"image/color"
"image/draw"
"github.com/BeatGlow/beatglow/ui/font"
"github.com/BeatGlow/display/pixel"
"github.com/BeatGlow/beatglow/app/font"
)
var (
@@ -29,28 +30,29 @@ var (
}
defaultMonoThemeStyles = Styles{
Window: defaultMonoObjectStyle,
Progress: defaultMonoObjectStyle.WithBorder(1),
Progress: defaultMonoObjectStyle,
Image: defaultMonoObjectStyle,
Graph: defaultMonoObjectStyle,
Text: TextStyle{
ObjectStyle: defaultMonoObjectStyle.WithMargin(1),
ObjectStyle: defaultMonoObjectStyle,
Font: font.SmoochSans,
},
}
defaultGrayObjectStyle = ObjectStyle{
Background: image.Black,
BackgroundColor: color.Black,
ForegroundColor: color.White,
BorderColor: color.Gray{Y: 0x7F},
BorderColor: color.Gray{Y: 0xBF},
}
defaultGrayThemeStyles = Styles{
Window: defaultGrayObjectStyle,
Progress: defaultGrayObjectStyle.WithBorder(1),
Progress: defaultGrayObjectStyle,
Image: defaultGrayObjectStyle,
Graph: defaultGrayObjectStyle,
Text: TextStyle{
ObjectStyle: defaultGrayObjectStyle.WithMargin(1),
Font: font.SmoochSans,
ObjectStyle: defaultGrayObjectStyle, // .WithMargin(1),
Font: font.Spleen5x8,
},
}
@@ -61,11 +63,11 @@ var (
}
defaultColorThemeStyles = Styles{
Window: defaultColorObjectStyle,
Progress: defaultColorObjectStyle.WithBorder(1).Inverse(),
Progress: defaultColorObjectStyle, // .WithBorder(1).Inverse(),
Image: defaultColorObjectStyle,
Graph: defaultColorObjectStyle,
Text: TextStyle{
ObjectStyle: defaultColorObjectStyle.WithMargin(1),
ObjectStyle: defaultColorObjectStyle, // .WithMargin(1),
Font: font.SmoochSans,
},
}
@@ -137,6 +139,22 @@ type ObjectStyle struct {
Stroke int
}
func (s ObjectStyle) WithBackgroundColor(c color.Color) ObjectStyle {
i := new(ObjectStyle)
*i = s
i.Background = nil
i.BackgroundColor = c
return *i
}
func (s ObjectStyle) WithForegroundColor(c color.Color) ObjectStyle {
i := new(ObjectStyle)
*i = s
i.Foreground = nil
i.ForegroundColor = c
return *i
}
func (s ObjectStyle) Inverse() ObjectStyle {
i := new(ObjectStyle)
*i = s
@@ -246,7 +264,30 @@ func (s ObjectStyle) Inner(i draw.Image) draw.Image {
type TextStyle struct {
ObjectStyle
Font *font.Font
Font font.Font
}
func (s TextStyle) WithBackgroundColor(c color.Color) TextStyle {
i := new(TextStyle)
*i = s
i.Background = nil
i.BackgroundColor = c
return *i
}
func (s TextStyle) WithForegroundColor(c color.Color) TextStyle {
i := new(TextStyle)
*i = s
i.Foreground = nil
i.ForegroundColor = c
return *i
}
func (s TextStyle) WithFont(font font.Font) TextStyle {
return TextStyle{
ObjectStyle: s.ObjectStyle,
Font: font,
}
}
type Edge struct {
+27 -11
View File
@@ -2,20 +2,23 @@ package widget
import (
"image"
"image/draw"
"sync"
"sync/atomic"
"github.com/sirupsen/logrus"
"github.com/BeatGlow/beatglow/app"
"github.com/BeatGlow/beatglow/draw"
"github.com/BeatGlow/beatglow/internal/safe"
)
type Base struct {
bounds safe.Rectangle
position safe.Point
widget atomic.Pointer[app.Widget]
mu sync.RWMutex
buffer draw.Image
hidden bool
visible bool
styles app.Styles
changed atomic.Bool
}
@@ -41,11 +44,8 @@ func (b *Base) Bounds() image.Rectangle {
}
func (b *Base) Move(p image.Point) app.Widget {
bounds := b.bounds.Load()
b.bounds.Store(image.Rectangle{
Min: p,
Max: bounds.Size(),
})
b.position.Store(p)
b.changed.Store(true)
return b.super()
}
@@ -57,42 +57,58 @@ func (b *Base) Resize(size image.Point) app.Widget {
}
func (b *Base) Hide(ctx app.Context) app.Widget {
log := logrus.WithField("widget", b.super())
if !b.IsVisible() {
log.Trace("widget is already invisible")
return b.super()
}
b.mu.Lock()
b.hidden = true
b.visible = false
b.mu.Unlock()
b.changed.Store(true)
/*
if widget := b.super(); widget != nil {
log.Trace("widget refresh triggering")
widget.Refresh(ctx)
} else {
log.Trace("base: no super to refresh!")
}
*/
return b.super()
}
func (b *Base) Show(ctx app.Context) app.Widget {
log := logrus.WithField("widget", b.super())
if b.IsVisible() {
log.Trace("widget is already visible")
return b.super()
}
b.mu.Lock()
b.hidden = false
b.visible = true
b.mu.Unlock()
b.changed.Store(true)
/*
if widget := b.super(); widget != nil {
log.Trace("widget refresh triggering")
widget.Refresh(ctx)
}
*/
return b.super()
}
func (b *Base) IsVisible() bool {
b.mu.RLock()
visible := !b.hidden
visible := b.visible
b.mu.RUnlock()
return visible
}
@@ -113,7 +129,7 @@ func (b *Base) SetStyles(styles app.Styles) app.Widget {
return b.super()
}
func (b *Base) Render(ctx app.Context) app.Widget {
func (b *Base) Refresh(ctx app.Context) app.Widget {
if !b.changed.CompareAndSwap(true, false) {
return b.super()
}
+77 -7
View File
@@ -2,8 +2,14 @@ package widget
import (
"image"
"image/color"
"github.com/makeworld-the-better-one/dither/v2"
"github.com/nfnt/resize"
"github.com/sirupsen/logrus"
"github.com/BeatGlow/beatglow/app"
"github.com/BeatGlow/display/pixel"
)
type Image struct {
@@ -19,31 +25,95 @@ func NewImage(size image.Point) *Image {
}
func (w *Image) String() string {
if w.image != nil {
return "image:" + w.image.Bounds().String()
}
return "image"
}
func (w *Image) Update(image image.Image, model color.Model) app.Widget {
log := logrus.WithField("widget", w.String())
max := w.Bounds().Size()
thumbnail := resize.Thumbnail(
uint(max.X), uint(max.Y),
convertImageFor(model, image),
resize.Lanczos3)
log.WithFields(logrus.Fields{
"size_max": max,
"size_org": image.Bounds().Size(),
"size_new": thumbnail.Bounds().Size(),
}).Debug("update image")
func (w *Image) Update(image image.Image) app.Widget {
w.mu.Lock()
w.image = image
w.image = thumbnail
w.mu.Unlock()
w.changed.Store(true)
return w
}
func (w *Image) Refresh(ctx app.Context) app.Widget {
func (w *Image) Refresh(ctx app.Context) bool {
log := logrus.WithField("widget", w.String())
if !w.IsVisible() {
return w
log.Trace("not refreshing; not visisble")
return false
}
if !w.changed.CompareAndSwap(true, false) {
return w
log.Trace("not refreshing; not changed")
return false
}
var refreshed bool
w.mu.RLock()
app.ImageCopyBounds(ctx.Display(), w.image, w.Bounds())
if w.image == nil {
log.Trace("not refreshing; not image")
} else {
log.WithField("size", w.Bounds().Size()).Trace("refreshing image")
app.ImageCopyBounds(ctx.Display(), w.image, w.Bounds().Add(w.position.Load()))
refreshed = true
}
w.mu.RUnlock()
return w
return refreshed
}
var ditherCache = make(map[color.Model]*dither.Ditherer)
func convertImageFor(model color.Model, image image.Image) image.Image {
var palette []color.Color
switch model {
case pixel.MonoModel:
palette = []color.Color{pixel.Off, pixel.On}
case pixel.Gray2Model:
for y := 0; y < 4; y++ {
v := uint8(y) * 0x3F
palette = append(palette, color.RGBA{v, v, v, 0xFF})
}
case pixel.Gray4Model:
for y := 0; y < 16; y++ {
v := uint8(y) * 0x0F
palette = append(palette, color.RGBA{v, v, v, 0xFF})
}
default:
return image
}
d, ok := ditherCache[model]
if !ok {
d = dither.NewDitherer(palette)
d.Matrix = dither.FloydSteinberg
d.Serpentine = true
ditherCache[model] = d
}
return d.Dither(image)
}
var _ app.Widget = (*Image)(nil)
+170
View File
@@ -0,0 +1,170 @@
package widget
import (
"fmt"
"image"
"image/color"
"reflect"
"github.com/sirupsen/logrus"
"github.com/BeatGlow/beatglow/app"
"github.com/BeatGlow/beatglow/app/font"
"github.com/BeatGlow/display/draw"
)
type Menu struct {
Base
items []MenuItem
index int
}
func NewMenu(size image.Point) *Menu {
w := new(Menu)
w.Extend(w)
w.Resize(size)
return w
}
func (w *Menu) String() string {
return "menu"
}
func (w *Menu) SetItems(items []MenuItem) *Menu {
w.mu.Lock()
w.items = append([]MenuItem{{
Text: "Go back",
Icon: "md_history",
Type: reflect.TypeOf(""),
}}, items...)
w.index = 0
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)
}
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 {
if w.buffer == nil {
w.buffer = app.BufferFor(ctx, size)
}
app.ImageClear(w.buffer)
var (
itemWidth = size.X - 8
itemHeight = 16
num = len(w.items)
max = size.Y / itemHeight
shift int
)
if w.index >= max {
shift = -(w.index - max)
} else {
shift = -w.index
}
for y := 0; y < max && y < num; y++ {
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}
)
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!")
}
}
// 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})
}
}
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)
)
-70
View File
@@ -1,70 +0,0 @@
package widget
import (
"image"
"github.com/BeatGlow/beatglow/app"
"github.com/BeatGlow/display/draw"
)
type Object struct {
active bool
width int
height int
pos image.Point
style app.ObjectStyle
canvas draw.Image
changed bool
}
func MakeObject(ctx app.Context, position image.Point, width, height int, style app.ObjectStyle) Object {
return Object{
width: width,
height: height,
pos: position,
style: style,
canvas: app.BufferFor(ctx, width, height),
changed: true,
}
}
func (w *Object) Bounds() image.Rectangle {
return image.Rect(0, 0, w.width, w.height)
}
func (w *Object) Position() image.Point {
return w.pos
}
func (w *Object) IsActive() bool {
return w.active
}
func (w *Object) Render() draw.Image {
if w.changed {
// Clear entire buffer.
app.ImageClear(w.canvas)
var (
bounds = w.canvas.Bounds()
outer = w.style.Outer(w.canvas)
)
// Background draws into outer region.
if w.style.Background != nil {
app.ImageCopy(outer, w.style.Background)
} else {
app.ImageFill(outer, w.style.BackgroundColor)
}
// Draw border
draw.Box(w.canvas, image.Rect(0, 0, bounds.Max.X, w.style.Border.Top), w.style.BorderColor)
draw.Box(w.canvas, image.Rect(0, bounds.Max.Y-w.style.Border.Bottom, bounds.Max.X, bounds.Max.Y), w.style.BorderColor)
draw.Box(w.canvas, image.Rect(0, 0, w.style.Border.Left, bounds.Max.Y), w.style.BorderColor)
draw.Box(w.canvas, image.Rect(bounds.Max.X-w.style.Border.Right, 0, bounds.Max.X, bounds.Max.Y), w.style.BorderColor)
// After redrawing mark the object as unchanged.
w.changed = false
}
return w.canvas
}
+404
View File
@@ -0,0 +1,404 @@
package widget
import (
"image"
"image/draw"
"math"
"sync/atomic"
"github.com/sirupsen/logrus"
"github.com/BeatGlow/audio"
"github.com/BeatGlow/audio/dsp"
"github.com/BeatGlow/audio/dsp/window"
"github.com/BeatGlow/audio/filter"
"github.com/BeatGlow/display/pixel"
"github.com/BeatGlow/beatglow/app"
"github.com/BeatGlow/beatglow/internal/calc"
"github.com/BeatGlow/beatglow/player"
)
// Spectrum analyzer widget.
//
// Can render mono and stereo spectrum analyzer or waterfall plots.
type Spectrum struct {
Base
minFrequency int
maxFrequency int
channels int
hold int
bins int
waterfall bool
analyzer *dsp.FrequencyPowerCalculator[float64]
samples [2]audio.Samples[float64] // samples without DC component
powers [2][]dsp.FrequencyPower // spectral powers
bands [2][]float64 // summarized spectral powers
peaks [2][][]float64 // peak levels
changed atomic.Bool
}
func NewSpectrum(size image.Point) *Spectrum {
bins := size.X / 4 / 1
w := &Spectrum{
minFrequency: 150,
maxFrequency: 15000,
channels: 1,
hold: 20,
bins: bins,
bands: makeMonoBands(bins),
peaks: makeMonoPeaks(bins),
analyzer: dsp.NewFrequencyPowerCalculator[float64](44100, window.Blackman1024),
}
w.Extend(w)
w.Resize(size)
return w
}
func (w *Spectrum) String() string {
channels := "mono"
variant := "analyzer"
if w.channels > 1 {
channels = "stereo"
}
if w.waterfall {
variant = "waterfall"
}
return channels + " " + variant
}
func (w *Spectrum) update(channels, bins int) {
w.mu.Lock()
w.channels = channels
w.bins = bins
if w.waterfall {
w.bins = w.Bounds().Dx() / w.channels
} else {
w.bins = w.Bounds().Dx() / 4 / w.channels
}
switch channels {
case 1:
w.bands = makeMonoBands(w.bins)
w.peaks = makeMonoPeaks(w.bins)
case 2:
w.bands = makeStereoBands(w.bins)
w.peaks = makeStereoPeaks(w.bins)
}
w.mu.Unlock()
w.changed.Store(true)
}
func (w *Spectrum) SetChannels(channels int) *Spectrum {
if w.waterfall {
w.update(channels, w.bounds.Load().Dx()/channels)
} else {
w.update(channels, w.bounds.Load().Dx()/channels/4)
}
return w
}
func (w *Spectrum) SetWaterfall(on bool) *Spectrum {
w.mu.Lock()
w.waterfall = on
w.mu.Unlock()
if w.waterfall {
w.update(w.channels, w.bounds.Load().Dx()/w.channels)
} else {
w.update(w.channels, w.bounds.Load().Dx()/w.channels/4)
}
return w
}
func (w *Spectrum) Resize(size image.Point) app.Widget {
w.update(w.channels, w.bins)
return w.Base.Resize(size)
}
func (w *Spectrum) Refresh(ctx app.Context) bool {
if !w.IsVisible() {
return false
}
bounds := w.bounds.Load()
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)
}
}
if w.waterfall {
w.refreshWaterfall(bounds)
} else {
w.refreshAnalyzer(bounds)
}
}
app.ImageCopyBounds(ctx.Display(), w.buffer, bounds.Add(w.position.Load()))
return true
}
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)
}
var (
width = bounds.Dx()
height = bounds.Dy()
)
switch w.channels {
case 1:
for i := range w.bands[0] {
w.drawBarMono(i, height)
}
case 2:
for i := range w.bands[0] {
w.drawBarStereo(0, i, width, height)
w.drawBarStereo(1, i, width, height)
}
}
}
func (w *Spectrum) drawBarMono(i, maxHeight int) {
offset := i * 4
height := int(float64(maxHeight)*w.bands[0][i] + .5)
for y := maxHeight - height; y < maxHeight; y++ {
colorY := pixel.Gray4{Y: 0xf - uint8(float64(y)/float64(maxHeight)*12+.5)}
for x := 0; x < 3; x++ {
w.buffer.Set(offset+x, y, colorY)
}
}
if w.hold <= 0 {
return
}
height = maxHeight - int(float64(maxHeight)*calc.Max(w.peaks[0][i])+5)
for x := 0; x < 3; x++ {
w.buffer.Set(offset+x, height, pixel.On)
}
}
func (w *Spectrum) drawBarStereo(channel, i, width, maxHeight int) {
var offset int
if channel == 0 {
offset = (width / 2) - (i+1)*4
} else {
offset = (width / 2) + i*4
}
height := int(float64(maxHeight)*w.bands[channel][i] + .5)
for y := maxHeight - height; y < maxHeight; y++ {
colorY := pixel.Gray4{Y: 0xf - uint8(float64(y)/float64(maxHeight)*12+.5)}
for x := 0; x < 3; x++ {
w.buffer.Set(offset+x, y, colorY)
}
}
if w.hold <= 0 {
return
}
height = maxHeight - int(float64(maxHeight)*calc.Max(w.peaks[channel][i])+5)
for x := 0; x < 3; x++ {
w.buffer.Set(offset+x, height, pixel.On)
}
}
func (w *Spectrum) refreshWaterfall(bounds image.Rectangle) {
// Move waterfall up.
switch buffer := w.buffer.(type) {
case *pixel.Gray2Image:
copy(buffer.Pix, buffer.Pix[buffer.Stride:])
case *pixel.Gray4Image:
copy(buffer.Pix, buffer.Pix[buffer.Stride:])
case *pixel.CRGB15Image:
copy(buffer.Pix, buffer.Pix[buffer.Stride:])
case *pixel.CRGB16Image:
copy(buffer.Pix, buffer.Pix[buffer.Stride:])
case *image.RGBA:
copy(buffer.Pix, buffer.Pix[buffer.Stride:])
default:
for y := bounds.Dy() - 1; y > 0; y-- {
draw.Draw(w.buffer, image.Rect(0, y, bounds.Dx(), y+1), w.buffer, image.Pt(0, y-1), draw.Src)
}
}
height := bounds.Dy()
if w.channels == 1 {
for i, v := range w.bands[0] {
w.drawMonoPoint(i, v, height)
}
}
}
func (w *Spectrum) drawMonoPoint(i int, level float64, maxHeight int) {
intesity := uint8(16*level + .5)
w.buffer.Set(i, maxHeight-1, pixel.Gray4{Y: intesity})
}
func (w *Spectrum) StatusChanged(ctx app.Context, status *player.Status) {
}
func (w *Spectrum) ProcessBuffer(buffer audio.Buffer[float64]) {
if w.changed.Load() {
// Previous rendition hasn't finished, discard buffer.
return
}
log := logrus.WithFields(logrus.Fields{
"widget": w.String(),
"channels": buffer.Channels(),
"samples": buffer.Samples(),
})
log.Trace("process audio buffer")
switch w.channels {
case 1:
// High pass filter on 50Hz to remove DC bias.
w.samples[0] = filter.HighPass(w.samples[0], buffer[0], 50, 44100)
// Calculate spectral densities.
w.powers[0] = w.analyzer.Apply(w.powers[0], w.samples[0])
case 2:
// High pass filter on 50Hz to remove DC bias.
w.samples[0] = filter.HighPass(w.samples[0], buffer[0], 50, 44100)
w.samples[1] = filter.HighPass(w.samples[1], buffer[1], 50, 44100)
// Calculate spectral densities.
w.powers[0] = w.analyzer.Apply(w.powers[0], w.samples[0])
w.powers[1] = w.analyzer.Apply(w.powers[1], w.samples[1])
}
for c := 0; c < w.channels; c++ {
// Adjust scale.
for i := range w.powers[c] {
w.powers[c][i].Magnitude /= 8
}
// Compress powers to visible bars.
var (
hpIndex = frequencyAbove(w.powers[c], w.minFrequency)
lpIndex = frequencyBelow(w.powers[c], w.maxFrequency)
)
summarizePowerBands(w.bands[c], w.powers[c][hpIndex:lpIndex], lpIndex-hpIndex)
// Calculate peaks per band.
if w.hold > 0 {
for i, v := range w.bands[c] {
w.peaks[c][i] = append(w.peaks[c][i], v)
for len(w.peaks[c][i]) > w.hold {
w.peaks[c][i] = w.peaks[c][i][1:]
}
}
}
}
// We're done here
w.changed.Store(true)
}
func toMono(dst []float64, src audio.Buffer[float64]) []float64 {
if dst == nil {
dst = make([]float64, len(src[0]))
}
for i := range dst {
dst[i] = (src[0][i] + src[1][i]) / 2
}
return dst
}
func summarizePowerBands(bands []float64, powers []dsp.FrequencyPower, samples int) {
var (
frequencyBinSize = 44100 / float64(samples)
frequencyMin = float64(powers[0].Frequency)
frequencyMax = float64(powers[len(powers)-1].Frequency)
frequencyScale = (frequencyMax - frequencyMin) / float64(len(bands))
)
for i := range bands {
var (
frequencyStart = frequencyMin + float64(i)*frequencyScale
frequencyEnd = frequencyMin + float64(i+1)*frequencyScale
binStart = int((frequencyStart / frequencyBinSize) + .5)
binEnd = int((frequencyEnd / frequencyBinSize) + .5)
)
var total float64
var count int
for bin := binStart; bin < binEnd; bin++ {
total += math.Min(powers[bin].Magnitude, 1)
count += 1
}
if count == 0 {
bands[i] = 0
} else {
bands[i] = total / float64(count)
}
}
}
func frequencyAbove(powers []dsp.FrequencyPower, frequency int) (i int) {
var power dsp.FrequencyPower
for i, power = range powers {
if power.Frequency >= frequency {
return
}
}
return
}
func frequencyBelow(powers []dsp.FrequencyPower, frequency int) (i int) {
var power dsp.FrequencyPower
for i = len(powers) - 1; i >= 0; i-- {
if power.Frequency <= frequency {
return
}
}
return
}
func makeMonoBands(n int) [2][]float64 {
return [2][]float64{
make([]float64, n),
nil,
}
}
func makeStereoBands(n int) [2][]float64 {
return [2][]float64{
make([]float64, n),
make([]float64, n),
}
}
func makeMonoPeaks(n int) [2][][]float64 {
return [2][][]float64{
make([][]float64, n),
nil,
}
}
func makeStereoPeaks(n int) [2][][]float64 {
return [2][][]float64{
make([][]float64, n),
make([][]float64, n),
}
}
var (
_ app.Widget = (*Spectrum)(nil)
_ app.StatusChangeHandler = (*Spectrum)(nil)
_ app.BufferProcessor = (*Spectrum)(nil)
)
+94 -29
View File
@@ -3,6 +3,10 @@ package widget
import (
"fmt"
"image"
"image/draw"
"time"
"github.com/sirupsen/logrus"
"github.com/BeatGlow/beatglow/app"
)
@@ -11,6 +15,11 @@ type Text struct {
Base
text string
bind *string
scroll image.Point
scrollDir int
scrollGap int
scrollLast time.Time
scrollRate time.Duration
}
func NewText(size image.Point) *Text {
@@ -27,14 +36,27 @@ func (w *Text) String() string {
return fmt.Sprintf("text:%q", w.text)
}
func (w *Text) SetStyle(style app.TextStyle) app.Widget {
func (w *Text) SetStyle(style app.TextStyle) *Text {
styles := w.Styles()
styles.Text = style
_ = w.SetStyles(styles)
logrus.Debugf("using font %#+v", style.Font)
return w
}
func (w *Text) Bind(text *string) app.Widget {
func (w *Text) SetScroll(dir, gap int, rate time.Duration) *Text {
w.mu.Lock()
w.scroll = image.Point{}
w.scrollDir = dir
w.scrollGap = gap
w.scrollLast = time.Now()
w.scrollRate = rate
w.mu.Unlock()
w.changed.Store(true)
return w
}
func (w *Text) Bind(text *string) *Text {
w.mu.Lock()
w.text = "--- intentionally set to garbage ---"
w.bind = text
@@ -43,13 +65,13 @@ func (w *Text) Bind(text *string) app.Widget {
return w
}
func (w *Text) Update(text string) app.Widget {
func (w *Text) Update(text string) *Text {
w.mu.Lock()
w.text = text
w.bind = nil
w.mu.Unlock()
width, height := w.styles.Text.Font.MeasureText(w.text)
width, height := w.styles.Text.Font.MeasureString(w.text)
bounds := w.bounds.Load()
bounds.Max = bounds.Min.Add(image.Pt(width, height))
w.bounds.Store(bounds)
@@ -58,52 +80,95 @@ func (w *Text) Update(text string) app.Widget {
return w
}
func (w *Text) Refresh(ctx app.Context) app.Widget {
if !w.IsVisible() {
return w
}
func (w *Text) Refresh(ctx app.Context) bool {
log := logrus.WithField("widget", w.String())
if !w.changed.CompareAndSwap(true, false) {
// Only bail if our bound value hasn't changed.
if w.bind == nil || (w.text == *w.bind) {
return w
}
if !w.IsVisible() {
log.Trace("not refreshing; not visisble")
return false
}
var (
resize bool
bounds image.Rectangle
)
if w.bind != nil {
w.text = *w.bind
}
width, height := w.styles.Text.Font.MeasureText(w.text)
now = time.Now()
changed = w.changed.CompareAndSwap(true, false)
bounds = w.bounds.Load()
size := bounds.Size()
if resize = (size.X != width || size.Y != height); resize {
bounds.Max = bounds.Min.Add(image.Pt(width, height))
)
// Update text with our bound value, if changed.
if w.bind != nil && w.text != *w.bind {
w.text = *w.bind
w.scroll.X = 0
changed = true
}
if w.buffer == nil || !resize {
w.buffer = app.BufferFor(ctx, bounds.Size())
// Mark the widget as changed if the buffer doesn't fit our text.
var (
resize image.Point
textWidth, textHeight = w.styles.Text.Font.MeasureString(w.text)
)
textWidth += w.scrollGap
if w.buffer == nil {
resize = image.Pt(textWidth, textHeight)
changed = true
} else if size := w.buffer.Bounds().Size(); size.X < textWidth || size.Y < textHeight {
resize = image.Pt(textWidth, textHeight)
changed = true
}
// Re-render if changed
if changed {
// Resize buffer if required.
if w.buffer == nil || resize.X+resize.Y > 0 {
log.WithField("size", resize).Debug("allocating new buffer")
w.buffer = app.BufferFor(ctx, resize)
}
// 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)
}
// Fill text.
inner := w.styles.Text.Inner(w.buffer)
if w.styles.Text.Foreground != nil {
w.styles.Text.Font.Draw(inner, image.Point{}, w.styles.Text.Foreground, w.text)
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 {
w.styles.Text.Font.Draw(inner, image.Point{}, image.NewUniform(w.styles.Text.ForegroundColor), w.text)
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)
}
}
app.ImageCopyBounds(ctx.Display(), w.buffer, w.Bounds())
// Scroll text if required.
scrollRequired := textWidth > bounds.Dx()
if scrollRequired && w.scrollDir != 0 && now.Sub(w.scrollLast) >= w.scrollRate {
w.scroll.X += w.scrollDir
if w.scroll.X > (textWidth + w.scrollGap) {
w.scroll.X = 0
} else if w.scroll.X < -(textWidth + w.scrollGap) {
w.scroll.X = 0
}
w.scrollLast = now
}
return w
//log.WithField("bounds", w.Bounds()).Debug("draw")
output := image.Image(w.buffer)
if scrollRequired {
output = app.HorizontalWrappingImage{Image: w.buffer}
}
draw.Draw(ctx.Display(), bounds.Add(w.position.Load()), output, w.scroll, draw.Src)
return true
}
var _ app.Widget = (*Text)(nil)
Loaded 100 of 223 files, more files were not shown because too many files have changed in this diff. Show more