tins2020/tooltip.go

73 lines
1.7 KiB
Go
Raw Normal View History

2020-05-14 06:29:23 +00:00
package tins2020
import "github.com/veandco/go-sdl2/sdl"
type Tooltip struct {
ControlBase
Text string
}
const tooltipBorderThickness = 1
const tooltipHorizontalPadding = 6
const tooltipVerticalPadding = 2
2020-05-14 06:29:23 +00:00
const tooltipMouseDistance = 12
func (t *Tooltip) ActualFontName() string {
if t.FontName == "" {
return "small"
}
return t.FontName
}
2020-05-14 06:29:23 +00:00
func (t *Tooltip) Handle(ctx *Context, event sdl.Event) bool {
if len(t.Text) == 0 {
return false
}
font := ctx.Fonts.Font(t.ActualFontName())
if font == nil {
font = ctx.Fonts.Font("default")
}
2020-05-14 06:29:23 +00:00
windowW, windowH, err := ctx.Renderer.GetOutputSize()
if err != nil {
return false
}
labelW, labelH, err := font.SizeUTF8(t.Text)
if err != nil {
return false
}
mouse := ctx.MousePosition
width := int32(labelW) + 2*tooltipBorderThickness + 2*tooltipHorizontalPadding
height := int32(labelH) + 2*tooltipBorderThickness + 2*tooltipVerticalPadding
2020-05-14 06:29:23 +00:00
left := mouse.X + tooltipMouseDistance
top := mouse.Y + tooltipMouseDistance
if left+width > windowW {
left = mouse.X - tooltipMouseDistance - width
}
if top+height > windowH {
top = mouse.Y - tooltipMouseDistance - height
}
t.Bounds = Rect(left, top, width, height)
return false
}
func (t *Tooltip) Render(ctx *Context) {
almostBlack := MustHexColor("#0000007f")
SetDrawColor(ctx.Renderer, almostBlack)
2020-05-14 06:29:23 +00:00
ctx.Renderer.FillRect(t.Bounds.SDLPtr())
almostWhite := MustHexColor("ffffff7f")
SetDrawColor(ctx.Renderer, almostWhite)
2020-05-14 06:29:23 +00:00
ctx.Renderer.DrawRect(t.Bounds.SDLPtr())
font := ctx.Fonts.Font(t.ActualFontName())
2020-05-14 06:29:23 +00:00
bottomLeft := Pt(t.Bounds.X+tooltipBorderThickness+tooltipHorizontalPadding, t.Bounds.Y+t.Bounds.H-tooltipBorderThickness-tooltipVerticalPadding)
2020-05-14 06:29:23 +00:00
font.RenderCopy(ctx.Renderer, t.Text, bottomLeft, White)
}