Files

140 lines
2.7 KiB
Go

package widget
import (
"image"
"image/color"
"image/draw"
"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 {
Base
image image.Image
}
func NewImage(size image.Point) *Image {
w := new(Image)
w.Extend(w)
w.Resize(size)
return w
}
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")
w.mu.Lock()
w.image = thumbnail
w.mu.Unlock()
w.changed.Store(true)
return w
}
func (w *Image) Refresh(ctx app.Context) bool {
log := logrus.WithField("widget", w.String())
if !w.changed.CompareAndSwap(true, false) {
log.Trace("not refreshing; not changed")
return false
}
var refreshed bool
w.mu.RLock()
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 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)
}
type Canvas struct {
Base
}
func NewCanvas(size image.Point, model color.Model) *Canvas {
w := new(Canvas)
w.buffer = app.BufferFor(model, size)
w.Extend(w)
return w
}
func (w *Canvas) Buffer() draw.Image {
return w.buffer
}
func (w *Canvas) String() string {
return "canvas:" + w.buffer.Bounds().Size().String()
}
func (w *Canvas) Refresh(ctx app.Context) bool {
app.ImageCopy(ctx.Display(), w.buffer)
return true
}
var _ app.Widget = (*Image)(nil)