Checkpoint

This commit is contained in:
maze authored and maze committed 2026-10-29 17:29:41 +01:00
1 parent 85a9ec684c
commit c5d6137fab
160 files changed
+76293 -387

No files matched your search

+32
View File
@@ -0,0 +1,32 @@
package widget
import (
"image"
"image/draw"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/display"
)
type base struct {
display display.Display
style ui.Style
position image.Point
buffer draw.Image
changed bool
}
func makeBase(display display.Display, at image.Point, width, height int) base {
m := display.ColorModel()
return base{
display: display,
style: ui.StylesFor(m).Default,
position: at,
buffer: ui.BufferFor(m, width, height),
}
}
func (w *base) SetStyle(style ui.Style) {
w.style = style
w.changed = true
}
+78
View File
@@ -0,0 +1,78 @@
package widget
import (
"image"
"image/draw"
"github.com/BeatGlow/display"
)
// Empty display.
type Empty struct {
// Display this widget renders on.
Display display.Display
}
func (w Empty) Render(_ bool) bool {
w.Display.Clear()
return true
}
// Image displays an image.
type Image struct {
// Display this widget renders on.
Display display.Display
// Position on the display.
Position image.Point
// SourcePoint is the point from which this image is copied onto the display.
SourcePoint image.Point
// DrawOp is the drawing operation.
DrawOp draw.Op
buffer image.Image
changed bool
}
func NewImage(display display.Display, at image.Point, im image.Image) *Image {
return &Image{
Display: display,
Position: at,
DrawOp: draw.Src,
buffer: im,
}
}
func (w *Image) Set(i image.Image) {
w.buffer = i
w.changed = true
}
func (w *Image) Render(redraw bool) bool {
if !(redraw || w.changed) {
return false
}
if w.buffer != nil {
r := w.buffer.Bounds()
if w.Position.Eq(Center) {
b := w.buffer.Bounds().Size()
r.Min = image.Point{}
if x := r.Dx(); b.X < x {
r.Min.X = (x - b.X) / 2
}
if y := r.Dy(); b.Y < y {
r.Min.Y = (y - b.Y) / 2
}
} else {
r.Min = r.Min.Add(w.Position)
}
draw.Draw(w.Display, r, w.buffer, w.SourcePoint, w.DrawOp)
}
w.changed = false
return true
}
+89
View File
@@ -0,0 +1,89 @@
package widget
import (
"image"
"image/draw"
"github.com/BeatGlow/beatglow/hardware"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/display"
)
type List struct {
base
Items []string
Index int
OnSelect func(index int)
fontHeight int
top int
changed bool
}
func NewList(display display.Display, at image.Point, width, height int) *List {
w := &List{
base: makeBase(display, at, width, height),
}
w.SetStyle(w.style)
return w
}
func (w *List) Rotary(event hardware.RotaryEvent) {
w.Index = (w.Index + event.Delta) % len(w.Items)
w.changed = true
}
func (w *List) RotaryPress(event hardware.RotaryPressEvent) {
if w.OnSelect != nil {
w.OnSelect(w.Index)
}
}
func (w *List) SetStyle(style ui.Style) {
w.style = style
_, w.fontHeight = w.style.Font.MeasureText("^<>%MX#gjy")
w.changed = true
}
func (w *List) Render(refresh bool) bool {
if !(refresh || w.changed) {
return false
}
ui.Clear(w.buffer)
var (
bounds = w.buffer.Bounds()
point = bounds.Min
max = bounds.Dy() / w.fontHeight
fg = image.NewUniform(w.style.Foreground)
bg = w.style.Background
)
if w.top >= max {
w.top = w.Index - max + 1
} else if w.Index < w.top {
w.top = w.Index
}
for row := w.top; row < len(w.Items) && point.Y < bounds.Max.Y; row++ {
box := image.Rectangle{Min: point, Max: point.Add(image.Pt(bounds.Dx(), w.fontHeight))}
if row == w.Index {
draw.Draw(w.buffer, box, fg, image.Point{}, draw.Src)
w.style.Font.Draw(w.buffer, box.Min, bg, w.Items[row])
} else {
draw.Draw(w.buffer, box, bg, image.Point{}, draw.Src)
w.style.Font.Draw(w.buffer, box.Min, fg, w.Items[row])
}
point = point.Add(image.Pt(0, w.fontHeight))
}
_ = ui.Refresh(w.display, w.buffer)
return true
}
var (
_ ui.Widget = (*List)(nil)
_ hardware.RotaryHandler = (*List)(nil)
_ hardware.RotaryPressHandler = (*List)(nil)
)
+88
View File
@@ -0,0 +1,88 @@
package widget
import (
"image"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/display"
"github.com/BeatGlow/display/draw"
"github.com/BeatGlow/display/pixel"
"github.com/sirupsen/logrus"
)
type Progress struct {
Display display.Display
Style ui.Style
Position image.Point
width int
height int
progress float64
buffer draw.Image
changed bool
}
func NewProgress(display display.Display, at image.Point, width, height int) *Progress {
logrus.WithFields(logrus.Fields{
"width": width,
"height": height,
"at": at,
}).Debug("new progress bar")
model := display.ColorModel()
w := &Progress{
Display: display,
Style: ui.StylesFor(model).Format,
Position: at,
width: width,
height: height,
buffer: ui.BufferFor(model, width, height),
}
w.Set(0)
return w
}
func (w *Progress) Set(progress float64) {
if progress < 0 {
progress = 0
}
if progress > 1 {
progress = 1
}
w.progress = progress
w.changed = true
}
func (w *Progress) SetStyle(style ui.Style) *Progress {
w.Style = style
return w
}
func (w *Progress) Render(redraw bool) bool {
if !(redraw || w.changed) {
return false
}
var stop = 1
if w.progress > 0 {
stop = 1 + int(float64(w.width-2)*w.progress+.5)
}
for y := 0; y < w.height; y++ {
for x := 0; x < w.width; x++ {
if ((x == 0 || x == w.width-1) && y != 0 && y != w.height-1) ||
((y == 0 || y == w.height-1) && x != 0 && x != w.width-1) {
//if (x != 0 && y == 0) || y == w.height-1 || x == 0 || x == w.width-1 || x < stop {
w.buffer.Set(x, y, w.Style.Foreground)
} else if x > 0 && x < stop {
w.buffer.Set(x, y, pixel.Gray4{Y: 0x77})
} else {
w.buffer.Set(x, y, w.Style.Background.At(x, y))
}
}
}
draw.Draw(w.Display, w.buffer.Bounds().Add(w.Position), w.buffer, image.Point{}, draw.Src)
w.changed = false
return true
}
var _ ui.Widget = (*Progress)(nil)
+147
View File
@@ -0,0 +1,147 @@
package widget
import (
"fmt"
"image"
"image/color"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/display"
"github.com/BeatGlow/display/draw"
"github.com/sirupsen/logrus"
)
type Scroller struct {
Display display.Display
Position image.Point
Style ui.Style
width int
height int
buffer draw.Image
mask image.Image
text string
dir int
scroll int
scrollWidth int
required bool
changed bool
}
func NewScroller(display display.Display, at image.Point, width, height int) *Scroller {
r := display.Bounds()
if width <= 0 {
width = r.Dx()
}
if height <= 0 {
height = r.Dy()
}
w := &Scroller{
Display: display,
Position: at,
width: width,
height: height,
dir: +1,
}
w.SetStyle(ui.StylesFor(display.ColorModel()).Track)
w.Set("")
return w
}
func (w *Scroller) Set(text string) *Scroller {
width, _ := w.Style.Font.MeasureText(text)
if w.required = width > w.width; w.required {
// add spaces to the text and re-measure
width, _ = w.Style.Font.MeasureText(text + " ")
}
if width < w.width {
width = w.width
}
logrus.WithFields(logrus.Fields{
"size": fmt.Sprintf("%dx%d", width, w.height),
"text": text,
"widget": "scroller",
}).Debug("create new buffer")
w.buffer = ui.BufferFor(w.Display.ColorModel(), width, w.height)
draw.Draw(w.buffer, w.buffer.Bounds(), w.Style.Background, image.Point{}, draw.Src)
w.Style.Font.Draw(w.buffer, image.Point{}, w.mask, text)
if w.required {
w.buffer = horizontalRepeatingImage{
Image: w.buffer,
Size: image.Pt(width, w.height),
}
}
w.changed = true
w.text = text
w.scroll = 0
w.scrollWidth = width
return w
}
func (w *Scroller) SetDir(dir int) *Scroller {
w.dir = dir
if w.text != "" {
w.Set(w.text)
}
return w
}
func (w *Scroller) SetStyle(style ui.Style) *Scroller {
w.Style = style
w.mask = image.NewUniform(w.Style.Foreground)
if w.text != "" {
w.Set(w.text)
}
return w
}
func (w *Scroller) nextFrame() {
if !w.required || w.dir == 0 {
return
}
w.scroll += w.dir
if w.scroll > w.scrollWidth || w.scroll < -w.scrollWidth {
w.scroll = 0
}
w.changed = true
}
func (w *Scroller) Render(redraw bool) bool {
w.nextFrame()
if !(redraw || w.changed) {
return false
}
sp := image.Pt(w.scroll, 0)
draw.Draw(w.Display, image.Rectangle{
Min: w.Position,
Max: w.Position.Add(image.Point{X: w.width, Y: w.height}),
}, w.buffer, sp, draw.Src)
w.changed = false
return true
}
type horizontalRepeatingImage struct {
draw.Image
Size image.Point
}
func (i horizontalRepeatingImage) At(x, y int) color.Color {
for x < 0 {
x += i.Size.X
}
for x >= i.Size.X {
x -= i.Size.X
}
return i.Image.At(x, y)
}
func (i horizontalRepeatingImage) Bounds() image.Rectangle {
b := i.Image.Bounds()
b.Min.X -= i.Size.X
b.Max.X += i.Size.X
return b
}
+262
View File
@@ -0,0 +1,262 @@
package widget
import (
"image"
"math"
"github.com/BeatGlow/audio"
"github.com/BeatGlow/audio/dsp"
"github.com/BeatGlow/audio/dsp/window"
"github.com/BeatGlow/audio/filter"
"github.com/BeatGlow/beatglow/internal/calc"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/display"
"github.com/BeatGlow/display/draw"
"github.com/BeatGlow/display/pixel"
)
const (
spectrumBandPixels = 7
spectrumPeakHold = 20
)
type Spectrum struct {
Display display.Display
Position image.Point
buffer draw.Image
width int
height int
mono []float64
bands []float64
peaks [][]float64
scale float64
thresholdDBFS float64
analyzer *dsp.FrequencyPowerCalculator[float64]
minFrequency int
maxFrequency int
hold int
waterfall bool
changed bool
}
func NewSpectrum(display display.Display, at image.Point, width, height int) *Spectrum {
bins := width / spectrumBandPixels
return &Spectrum{
Display: display,
Position: at,
buffer: ui.BufferFor(display.ColorModel(), width, height),
width: width,
height: height,
bands: make([]float64, bins),
peaks: make([][]float64, bins),
thresholdDBFS: -dsp.SQNR(16),
analyzer: dsp.NewFrequencyPowerCalculator[float64](44100, window.Blackman(1024)),
minFrequency: 500,
maxFrequency: 15000,
hold: spectrumPeakHold,
scale: 1.0,
}
}
func (w *Spectrum) SetWaterwall(on bool) {
w.waterfall = on
var bins int
if on {
bins = w.width
} else {
bins = w.width / spectrumBandPixels
}
w.bands = make([]float64, bins)
w.peaks = make([][]float64, bins)
}
func (w *Spectrum) SetRange(min, max int) {
if min > max {
min, max = max, min
}
w.minFrequency = min
w.maxFrequency = max
}
func (w *Spectrum) SetHold(hold int) {
if hold < 1 {
hold = 1
}
w.hold = hold
}
func (w *Spectrum) Render(redraw bool) bool {
if !(redraw || w.changed) {
return false
}
if w.waterfall {
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 := w.height - 1; y > 0; y-- {
draw.Draw(w.buffer, image.Rect(0, y, w.width, y+1), w.buffer, image.Pt(0, y-1), draw.Src)
}
}
for x, level := range w.bands {
intesity := uint8(16*level + .5)
w.buffer.Set(x, w.height-1, pixel.Gray4{Y: intesity})
}
} else {
draw.Draw(w.buffer, w.buffer.Bounds(), image.Black, image.Point{}, draw.Src)
for i, level := range w.bands {
height := int(float64(w.height)*level + .5)
offset := i * spectrumBandPixels
//logrus.Infof("band %d at height %d (%f)", i, height, level)
for y := w.height - height; y < w.height; y++ {
for x := 0; x < spectrumBandPixels-1; x++ {
w.buffer.Set(offset+x, y, pixel.Gray4{Y: 0x8})
}
}
if w.hold <= 0 {
continue
}
height = w.height - int(float64(w.height)*calc.Max(w.peaks[i])+.5)
for x := 0; x < spectrumBandPixels-1; x++ {
w.buffer.Set(offset+x, height, pixel.On)
}
}
}
draw.Draw(w.Display, w.buffer.Bounds().Add(w.Position), w.buffer, image.Point{}, draw.Src)
return true
}
func (w *Spectrum) ProcessBuffer(buffer audio.Buffer[float64]) {
// Dynamically resize if needed.
if samples := buffer.Samples(); len(w.mono) != samples {
w.mono = make([]float64, samples)
}
// Convert buffer to mono.
buffer.ToMono(w.mono)
// High pass filter on 50Hz to remove DC bias.
w.mono = filter.HighPass(nil, w.mono, 50, 44100)
// Calculate spectral powers.
powers := w.analyzer.Apply(nil, w.mono)
// Adjust scale
for _, v := range powers {
w.scale = math.Min(math.Max(w.scale, v.Magnitude), 8)
}
// Compress powers to our visible bins.
var (
frequencyBinSize = 44100 / float64(len(w.mono))
frequencyMin = float64(powers[0].Frequency)
frequencyMax = float64(powers[len(powers)-1].Frequency)
frequencyScale = (frequencyMax - frequencyMin) / float64(len(w.bands))
)
for i := range w.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/w.scale, 1)
count += 1
}
if count == 0 {
w.bands[i] = 0
} else {
w.bands[i] = total / float64(count)
}
}
// Peak level per band.
for i, v := range w.bands {
w.peaks[i] = append(w.peaks[i], v)
if len(w.peaks[i]) > w.hold {
w.peaks[i] = w.peaks[i][1:]
}
}
/*
logrus.Infof("%d peaks from %d samples in %dHz-%dHz: %f..%f %f..%f [%d/%d] scale %f",
len(w.bands), len(powers),
powers[0].Frequency, powers[len(powers)-1].Frequency,
calc.Min(w.bands), calc.Max(w.bands),
calc.Min(w.mono), calc.Max(w.mono),
buffer.Channels(), buffer.Samples(),
w.scale)
*/
w.changed = true
}
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
}
+217
View File
@@ -0,0 +1,217 @@
package widget
import (
"image"
"image/draw"
"github.com/BeatGlow/audio"
"github.com/BeatGlow/audio/dsp"
"github.com/BeatGlow/audio/dsp/window"
"github.com/BeatGlow/audio/filter"
"github.com/BeatGlow/beatglow/internal/calc"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/display"
"github.com/BeatGlow/display/pixel"
)
type StereoSpectrum struct {
Display display.Display
Position image.Point
buffer draw.Image
height int
width int
bands [2][]float64
peaks [2][][]float64
samples [2]audio.Samples[float64]
power [2][]dsp.FrequencyPower
analyzer *dsp.FrequencyPowerCalculator[float64]
minFrequency int
maxFrequency int
hold int
waterfall bool
changed bool
}
func NewStereoSpectrum(display display.Display, at image.Point, width, height int) *StereoSpectrum {
bins := width / spectrumBandPixels / 2
return &StereoSpectrum{
Display: display,
Position: at,
buffer: ui.BufferFor(display.ColorModel(), width, height),
height: height,
width: width,
bands: makeStereoBands(bins),
peaks: makeStereoPeaks(bins),
analyzer: dsp.NewFrequencyPowerCalculator[float64](44100, window.Blackman1024),
minFrequency: 500,
maxFrequency: 15000,
hold: spectrumPeakHold,
}
}
func (w *StereoSpectrum) SetWaterwall(on bool) {
w.waterfall = on
var bins int
if on {
bins = w.width / 2
} else {
bins = w.width / spectrumBandPixels / 2
}
w.bands = makeStereoBands(bins)
w.peaks = makeStereoPeaks(bins)
}
func (w *StereoSpectrum) SetRange(min, max int) {
if min > max {
min, max = max, min
}
w.minFrequency = min
w.maxFrequency = max
}
func (w *StereoSpectrum) SetHold(hold int) {
w.hold = hold
}
func (w *StereoSpectrum) Render(refresh bool) bool {
if !(refresh || w.changed) {
return false
}
bounds := w.buffer.Bounds()
//draw.Draw(w.buffer, bounds, image.Black, image.Point{}, draw.Src)
if w.waterfall {
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 := w.height - 1; y > 0; y-- {
draw.Draw(w.buffer, image.Rect(0, y, w.width, y+1), w.buffer, image.Pt(0, y-1), draw.Src)
}
}
for i := range w.bands[0] {
w.drawPoints(0, i)
w.drawPoints(1, i)
}
} else {
draw.Draw(w.buffer, w.buffer.Bounds(), image.Black, image.Point{}, draw.Src)
for i := range w.bands[0] {
w.drawBar(0, i)
w.drawBar(1, i)
}
}
draw.Draw(w.Display, bounds.Add(w.Position), w.buffer, image.Point{}, draw.Src)
return true
}
func (w *StereoSpectrum) drawBar(channel, i int) {
var offset int
if channel == 0 {
offset = (w.width / 2) - (i+1)*spectrumBandPixels
} else {
offset = (w.width / 2) + i*spectrumBandPixels
}
height := int(float64(w.height)*w.bands[channel][i] + .5)
for y := w.height - height; y < w.height; y++ {
colorY := pixel.Gray4{Y: 0xf - uint8(float64(y)/float64(w.height)*12+.5)}
for x := 0; x < spectrumBandPixels-1; x++ {
w.buffer.Set(offset+x, y, colorY)
}
}
if w.hold <= 0 {
return
}
height = w.height - int(float64(w.height)*calc.Max(w.peaks[channel][i])+5)
for x := 0; x < spectrumBandPixels-1; x++ {
w.buffer.Set(offset+x, height, pixel.On)
}
}
func (w *StereoSpectrum) drawPoints(channel, i int) {
var offset int
if channel == 0 {
offset = (w.width / 2) - (i + 1)
} else {
offset = (w.width / 2) + i
}
intesity := uint8(16*w.bands[channel][i] + .5)
w.buffer.Set(offset, w.height-1, pixel.Gray4{Y: intesity})
}
func (w *StereoSpectrum) ProcessBuffer(buffer audio.Buffer[float64]) {
var (
channels = buffer.Channels()
)
// Convert buffers to mono and high pass on 50Hz.
if channels == 1 { // unlikely
w.samples[0] = filter.HighPass(w.samples[0], buffer[0], 50, 44100)
w.samples[1] = w.samples[0]
} else {
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 powers.
w.power[0] = w.analyzer.Apply(w.power[0], w.samples[0])
w.power[1] = w.analyzer.Apply(w.power[1], w.samples[1])
// Adjust scale.
for i := range w.power[0] {
w.power[0][i].Magnitude /= 8
w.power[1][i].Magnitude /= 8
}
// Compress powers to our visible bars.
var (
highPassIndex = frequencyAbove(w.power[0], w.minFrequency)
lowPassIndex = frequencyBelow(w.power[0], w.maxFrequency)
)
summarizePowerBands(w.bands[0], w.power[0][highPassIndex:lowPassIndex], lowPassIndex-highPassIndex)
summarizePowerBands(w.bands[1], w.power[1][highPassIndex:lowPassIndex], lowPassIndex-highPassIndex)
// Calculate peaks per band.
if w.hold > 0 {
for c := range w.bands {
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:]
}
}
}
}
w.changed = true
}
func makeStereoBands(n int) [2][]float64 {
return [2][]float64{
make([]float64, n),
make([]float64, n),
}
}
func makeStereoPeaks(n int) [2][][]float64 {
return [2][][]float64{
make([][]float64, n),
make([][]float64, n),
}
}
+108
View File
@@ -0,0 +1,108 @@
package widget
import (
"fmt"
"image"
"math"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/display"
"github.com/BeatGlow/display/draw"
"github.com/sirupsen/logrus"
)
const (
// CenterX is a position coordinate to indicate the widget should be centered horizontally.
CenterX = math.MinInt
// CenterY is a position coordinate to indicate the widget should be centered vertically.
CenterY = math.MinInt
)
// Center magic position shortcut.
var Center = image.Point{
X: CenterX,
Y: CenterY,
}
// Text widget can render text.
type Text struct {
Display display.Display
Position image.Point
Style ui.Style
buffer draw.Image
mask image.Image
text string
changed bool
}
func NewText(display display.Display, at image.Point) *Text {
return &Text{
Display: display,
Position: at,
}
}
func (w *Text) Set(text string) *Text {
width, height := w.Style.Font.MeasureText(text)
if w.buffer == nil || !w.buffer.Bounds().Eq(image.Rect(0, 0, width, height)) {
logrus.WithFields(logrus.Fields{
"size": fmt.Sprintf("%dx%d", width, height),
"text": text,
"widget": "text",
}).Debug("create new buffer")
w.buffer = ui.BufferFor(w.Display.ColorModel(), width, height)
}
draw.Draw(w.buffer, w.buffer.Bounds(), w.Style.Background, image.Point{}, draw.Src)
w.Style.Font.Draw(w.buffer, image.Point{}, w.mask, text)
w.text = text
w.changed = true
return w
}
func (w *Text) SetStyle(style ui.Style) *Text {
w.Style = style
if style.FontSize > 0 {
w.Style.Font.SetPointSize(style.FontSize)
}
w.mask = image.NewUniform(w.Style.Foreground)
if w.text != "" {
w.Set(w.text)
}
return w
}
func (w *Text) Render(redraw bool) bool {
if !(redraw || w.changed) {
return false
}
var (
r = w.Display.Bounds()
displaySize = r.Size()
bufferSize = w.buffer.Bounds().Size()
)
if w.Position.X == CenterX {
if bufferSize.X < displaySize.X {
r.Min.X = (displaySize.X - bufferSize.X) / 2
}
} else {
r.Min.X += w.Position.X
}
if w.Position.Y == CenterY {
if bufferSize.Y < displaySize.Y {
r.Min.Y = (displaySize.Y - bufferSize.Y) / 2
}
} else {
r.Min.Y += w.Position.Y
}
draw.Draw(w.Display, r, w.buffer, image.Point{}, draw.Src)
w.changed = false
return true
}
+76
View File
@@ -0,0 +1,76 @@
package widget
import (
"image"
"math"
)
const (
halfPi = math.Pi / 2
)
type Transitioner interface {
Transition(float64) float64
}
type TransitionFunc func(float64) float64
func (f TransitionFunc) Transition(x float64) float64 { return f(x) }
var (
Linear = TransitionFunc(func(x float64) float64 { return x })
Exponential = TransitionFunc(func(x float64) float64 { return math.Pow(2, 8*(x-1)) })
Circular = TransitionFunc(func(x float64) float64 { return 1 - math.Sin(math.Acos(x)) })
Sine = TransitionFunc(func(x float64) float64 { return 1 - math.Sin(x*halfPi) })
Elastic = TransitionFunc(func(x float64) float64 { return math.Pow(2, 10*(x-1)) * math.Cos(20*x*math.Pi/3) })
Bounce = TransitionFunc(bounce)
)
func bounce(x float64) (v float64) {
for a, b := 0.0, 1.0; true; a, b = a+b, b/2 {
if x >= (7-4*a)/11 {
v = b*b - math.Pow((11-6*a-11*x)/4, 2)
break
}
}
return
}
type PointTransition struct {
start, final image.Point
t Transitioner
dx, dy float64
step, steps int
}
func NewPointTransition(final image.Point, t Transitioner) *PointTransition {
return &PointTransition{
final: final,
t: t,
}
}
// Start a new transition for point at start to final.
func (p *PointTransition) Start(start image.Point, steps int) {
p.start = start
p.dx = float64(p.final.X-start.X) / float64(steps)
p.dy = float64(p.final.Y-start.Y) / float64(steps)
}
// Next step.
func (p *PointTransition) Next() (at image.Point, done bool) {
if p.step >= p.steps {
return p.final, true
}
p.step++
tx := 1.0
if p.t != nil {
tx = p.t.Transition(float64(p.step) / float64(p.steps))
}
at = p.start
at.X += int(p.dx * float64(p.step) * tx)
at.Y += int(p.dy * float64(p.step) * tx)
return
}
+111
View File
@@ -0,0 +1,111 @@
package widget
import (
"image"
"image/draw"
"github.com/BeatGlow/audio"
"github.com/BeatGlow/beatglow/ui"
"github.com/BeatGlow/display"
"github.com/BeatGlow/display/pixel"
)
type WaveForm struct {
Display display.Display
Position image.Point
buffer draw.Image
height int
width int
bins int
level [2][]float64
changed bool
}
func NewWaveform(display display.Display, at image.Point, width, height int) *WaveForm {
bins := width / 2
return &WaveForm{
Display: display,
Position: at,
buffer: ui.BufferFor(display.ColorModel(), width, height),
width: width,
height: height,
bins: bins,
}
}
func (w *WaveForm) Render(refresh bool) bool {
if !(refresh || w.changed) {
return false
}
draw.Draw(w.buffer, w.buffer.Bounds(), image.Black, image.Point{}, draw.Src)
for i := range w.level[0] {
w.drawLevel(0, i)
w.drawLevel(1, i)
}
draw.Draw(w.Display, w.buffer.Bounds().Add(w.Position), w.buffer, image.Point{}, draw.Src)
return true
}
func (w *WaveForm) drawLevel(channel, i int) {
var offset = (w.width / 2)
if channel == 0 {
offset -= i
} else {
offset += i
}
y := w.height/2 + int(float64(w.height/2)*w.level[channel][i]+.5)
w.buffer.Set(offset, y, pixel.On)
}
func (w *WaveForm) ProcessBuffer(buffer audio.Buffer[float64]) {
var (
channels = buffer.Channels()
)
if channels == 1 {
w.level[0] = condenseSamples(w.level[0], buffer[0], w.bins)
w.level[1] = w.level[0]
} else {
w.level[0] = condenseSamples(w.level[0], buffer[0], w.bins)
w.level[1] = condenseSamples(w.level[1], buffer[1], w.bins)
}
w.changed = true
}
// condenseSamples reduces the input samples to a fixed number of points.
// It aggregates values within each segment using averaging.
func condenseSamples(dst, src []float64, targetWidth int) []float64 {
if len(dst) != targetWidth {
dst = make([]float64, targetWidth)
}
if len(src) <= targetWidth {
// If the buffer is smaller than or equal to the target width, return as is.
copy(dst, src)
return dst
}
binSize := float64(len(src)) / float64(targetWidth)
for i := 0; i < targetWidth; i++ {
start := int(float64(i) * binSize)
end := int(float64(i+1) * binSize)
if end > len(src) {
end = len(src)
}
// Compute the average for the segment.
sum := 0.0
for j := start; j < end; j++ {
sum += src[j]
}
dst[i] = sum / float64(end-start)
}
return dst
}