109 lines
2.2 KiB
Go
109 lines
2.2 KiB
Go
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
|
|
}
|