diff options
Diffstat (limited to 'widget.go')
| -rw-r--r-- | widget.go | 116 |
1 files changed, 116 insertions, 0 deletions
diff --git a/widget.go b/widget.go new file mode 100644 index 0000000..d38f448 --- /dev/null +++ b/widget.go @@ -0,0 +1,116 @@ +package main + +import ( + "fmt" + "math/bits" + "strconv" + "strings" + + "gioui.org/layout" + "gioui.org/text" + "gioui.org/unit" + "gioui.org/widget" + "gioui.org/widget/material" +) + +type Float struct { + val float32 + editor widget.Editor + th *material.Theme +} + +func NewFloat(th *material.Theme) Float { + f := Float{th: th} + f.editor.SetText(fmt.Sprintf("%.2f", f.val)) + f.editor.SingleLine = true + f.editor.Alignment = text.Middle + return f +} + +func (f *Float) Set(v float32) { + f.val = v + f.editor.SetText(fmt.Sprintf("%.2f", f.val)) +} + +func (f *Float) Layout(gtx layout.Context) layout.Dimensions { + inputString := f.editor.Text() + inputString = strings.TrimSpace(inputString) + inputFloat, err := strconv.ParseFloat(inputString, 32) + if err != nil { + f.editor.SetText("") + } else { + f.val = float32(inputFloat) + } + + ed := material.Editor(f.th, &f.editor, "") + + border := widget.Border{ + Color: black, + CornerRadius: unit.Dp(3), + Width: unit.Dp(2), + } + + inset := layout.Inset{ + Top: unit.Dp(1), + Bottom: unit.Dp(1), + Left: unit.Dp(3), + Right: unit.Dp(3), + } + + return border.Layout(gtx, + func(gtx layout.Context) layout.Dimensions { + return inset.Layout(gtx, ed.Layout) + }, + ) +} + +type Int struct { + val int + editor widget.Editor + th *material.Theme +} + +func NewInt(th *material.Theme) Int { + i := Int{th: th} + i.editor.SetText(fmt.Sprintf("%d", i.val)) + i.editor.SingleLine = true + i.editor.Alignment = text.Middle + return i +} + +func (i *Int) Set(v int) { + i.val = v + i.editor.SetText(fmt.Sprintf("%d", i.val)) +} + +func (i *Int) Layout(gtx layout.Context) layout.Dimensions { + inputString := i.editor.Text() + inputString = strings.TrimSpace(inputString) + inputInt, err := strconv.ParseInt(inputString, 10, bits.UintSize) + if err != nil { + i.editor.SetText("") + } else { + i.val = int(inputInt) + } + + ed := material.Editor(i.th, &i.editor, "") + + border := widget.Border{ + Color: black, + CornerRadius: unit.Dp(3), + Width: unit.Dp(2), + } + + inset := layout.Inset{ + Top: unit.Dp(1), + Bottom: unit.Dp(1), + Left: unit.Dp(3), + Right: unit.Dp(3), + } + + return border.Layout(gtx, + func(gtx layout.Context) layout.Dimensions { + return inset.Layout(gtx, ed.Layout) + }, + ) +} |