gui/views/view_constrain.go

49 lines
984 B
Go
Raw Permalink Normal View History

2023-01-22 12:38:03 +01:00
package views
import (
2023-01-22 12:40:56 +01:00
"git.milar.in/milarin/gmath"
2023-01-22 12:38:03 +01:00
"git.milar.in/milarin/gui"
)
// ConstrainView is a gui.Wrapper which constrains the dimensions of its View
type ConstrainView struct {
gui.WrapperTmpl
MaxWidth int
MaxHeight int
}
var _ gui.Wrapper = &ConstrainView{}
func NewConstrainView(view gui.View, maxWidth, maxHeight int) *ConstrainView {
v := new(ConstrainView)
v.SetView(view)
v.Constrain(maxWidth, maxHeight)
return v
}
func (v *ConstrainView) Constrain(maxWidth, maxHeight int) {
v.MaxWidth, v.MaxHeight = maxWidth, maxHeight
}
func (v *ConstrainView) Layout(ctx gui.AppContext) (prefWidth, prefHeight int) {
if v.View() == nil {
return v.MaxWidth, v.MaxHeight
}
vw, vh := v.View().Layout(ctx)
if v.MaxWidth >= 0 {
2023-01-22 12:40:56 +01:00
prefWidth = iff(vw >= 0, gmath.Min(vw, v.MaxWidth), v.MaxWidth)
2023-01-22 12:38:03 +01:00
} else {
prefWidth = vw
}
if v.MaxHeight >= 0 {
2023-01-22 12:40:56 +01:00
prefHeight = iff(vh >= 0, gmath.Min(vh, v.MaxHeight), v.MaxHeight)
2023-01-22 12:38:03 +01:00
} else {
prefHeight = vh
}
return
}