gui/layouts/utils.go
2023-01-22 12:38:03 +01:00

96 lines
1.6 KiB
Go

package layouts
import (
"image"
"math"
"git.milar.in/milarin/gui"
)
func min(x, y int) int {
if x < y {
return x
}
return y
}
func max(x, y int) int {
if x > y {
return x
}
return y
}
func limit(v, minv, maxv int) int {
return min(max(v, minv), maxv)
}
func iff[T any](condition bool, trueValue, falseValue T) T {
if condition {
return trueValue
}
return falseValue
}
type LayoutResult struct {
Sizes map[gui.View]gui.Size
Sum gui.Size
Min gui.Size
Max gui.Size
Pref gui.Size
Count int
VerticalNegativeCount int
HorizontalNegativeCount int
}
func CalculateLayoutResult(ctx gui.AppContext, views []gui.View) *LayoutResult {
result := &LayoutResult{
Sizes: map[gui.View]gui.Size{},
Sum: gui.Size{Width: 0, Height: 0},
Min: gui.Size{Width: math.MaxInt, Height: math.MaxInt},
Max: gui.Size{Width: -1, Height: -1},
Count: 0,
VerticalNegativeCount: 0,
HorizontalNegativeCount: 0,
}
for _, view := range views {
if view == nil {
continue
}
result.Count++
width, height := view.Layout(ctx)
result.Sizes[view] = gui.Size{Width: width, Height: height}
if width > 0 {
result.Sum.Width += width
result.Min.Width = min(result.Min.Width, width)
result.Max.Width = max(result.Max.Width, width)
} else if width < 0 {
result.HorizontalNegativeCount++
}
if height > 0 {
result.Sum.Height += height
result.Min.Height = min(result.Min.Height, height)
result.Max.Height = max(result.Max.Height, height)
} else if height < 0 {
result.VerticalNegativeCount++
}
}
return result
}
func rect(x, y, w, h int) image.Rectangle {
return image.Rect(x, y, x+w, y+h)
}