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
+14770 -18352

No files matched your search

+39 -23
View File
@@ -2,22 +2,25 @@ 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
widget atomic.Pointer[app.Widget]
mu sync.RWMutex
buffer draw.Image
hidden bool
styles app.Styles
changed atomic.Bool
bounds safe.Rectangle
position safe.Point
widget atomic.Pointer[app.Widget]
mu sync.RWMutex
buffer draw.Image
visible bool
styles app.Styles
changed atomic.Bool
}
func (b *Base) Extend(w app.Widget) {
@@ -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 {
widget.Refresh(ctx)
}
/*
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 {
widget.Refresh(ctx)
}
/*
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()
}
+78 -8
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 {
return "image:" + w.image.Bounds().String()
if w.image != nil {
return "image:" + w.image.Bounds().String()
}
return "image"
}
func (w *Image) Update(image image.Image) app.Widget {
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")
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)
)
+102 -37
View File
@@ -3,14 +3,23 @@ package widget
import (
"fmt"
"image"
"image/draw"
"time"
"github.com/sirupsen/logrus"
"github.com/BeatGlow/beatglow/app"
)
type Text struct {
Base
text string
bind *string
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
now = time.Now()
changed = w.changed.CompareAndSwap(true, false)
bounds = w.bounds.Load()
)
if w.bind != nil {
// Update text with our bound value, if changed.
if w.bind != nil && w.text != *w.bind {
w.text = *w.bind
}
width, height := w.styles.Text.Font.MeasureText(w.text)
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))
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
}
if w.styles.Text.Background != nil {
app.ImageCopy(w.buffer, w.styles.Text.Background)
} else {
app.ImageFill(w.buffer, w.styles.Text.BackgroundColor)
// 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 {
log.WithField("text", w.text).
WithField("inner", inner).
Debug("text canvas with foreground mask")
w.styles.Text.Font.Draw(inner, w.scroll, w.styles.Text.Foreground, w.text)
} else {
log.WithField("text", w.text).
WithField("inner", inner).
WithField("color", w.styles.Text.ForegroundColor).
Debug("text canvas with foreground color")
w.styles.Text.Font.Draw(inner, w.scroll, image.NewUniform(w.styles.Text.ForegroundColor), w.text)
}
}
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)
} else {
w.styles.Text.Font.Draw(inner, image.Point{}, image.NewUniform(w.styles.Text.ForegroundColor), w.text)
// 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
}
app.ImageCopyBounds(ctx.Display(), w.buffer, w.Bounds())
//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 w
return true
}
var _ app.Widget = (*Text)(nil)