Files

143 lines
2.4 KiB
Go

package widget
import (
"image"
"image/draw"
"sync"
"sync/atomic"
"github.com/sirupsen/logrus"
"github.com/BeatGlow/beatglow/app"
"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
visible bool
styles app.Styles
changed atomic.Bool
}
func (b *Base) Extend(w app.Widget) {
if widget := b.widget.Load(); widget != nil {
return
}
b.widget.Store(&w)
b.changed.Store(true)
}
func (b *Base) super() app.Widget {
if widget := b.widget.Load(); widget != nil {
return *widget
}
return nil
}
func (b *Base) Bounds() image.Rectangle {
return b.bounds.Load()
}
func (b *Base) Move(p image.Point) app.Widget {
b.position.Store(p)
b.changed.Store(true)
return b.super()
}
func (b *Base) Resize(size image.Point) app.Widget {
bounds := b.bounds.Load()
bounds.Max = bounds.Min.Add(size)
b.bounds.Store(bounds)
return b.super()
}
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.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.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.visible
b.mu.RUnlock()
return visible
}
func (b *Base) Styles() app.Styles {
b.mu.RLock()
styles := b.styles
b.mu.RUnlock()
return styles
}
func (b *Base) SetStyles(styles app.Styles) app.Widget {
b.mu.Lock()
b.styles = styles
b.mu.Unlock()
b.changed.Store(true)
return b.super()
}
func (b *Base) Refresh(ctx app.Context) app.Widget {
if !b.changed.CompareAndSwap(true, false) {
return b.super()
}
if b.buffer == nil {
b.buffer = app.BufferFor(ctx.Display().ColorModel(), b.Bounds().Size())
}
return b.super()
}