package ui import ( "fmt" "image/color" "github.com/llgcode/draw2d/draw2dimg" "github.com/llgcode/draw2d/draw2dkit" "opslag.de/schobers/geom" "opslag.de/schobers/zntg/allg5" ) type CheckboxValueChangedFn func(bool) func drawCheckedBitmap(fill, stroke color.Color) *allg5.Bitmap { return drawBitmap(checkboxSize, checkboxSize, func(gc *draw2dimg.GraphicContext) { var size float64 = checkboxSize var margin float64 = checkboxMargin gc.SetFillColor(fill) draw2dkit.RoundedRectangle(gc, margin, margin, size-margin, size-margin, margin, margin) gc.Fill() gc.SetStrokeColor(stroke) gc.SetLineWidth(1.5) gc.MoveTo(7, 12) gc.LineTo(10.5, 15.5) gc.LineTo(17, 9) gc.Stroke() }) } func drawUncheckedBitmap(fill, stroke color.Color) *allg5.Bitmap { return drawBitmap(checkboxSize, checkboxSize, func(gc *draw2dimg.GraphicContext) { var size float64 = checkboxSize var margin float64 = checkboxMargin gc.SetLineWidth(2) gc.SetStrokeColor(stroke) draw2dkit.RoundedRectangle(gc, margin+1, margin+1, size-margin-1, size-margin-1, margin-1, margin-1) gc.Stroke() }) } type Checkbox struct { ControlBase Value bool Text string OnChanged CheckboxValueChangedFn checked *allg5.Bitmap unchecked *allg5.Bitmap } func (c *Checkbox) Created(ctx Context, p Container) error { var err = c.ControlBase.Created(ctx, p) if nil != err { return err } var plt = ctx.Palette() c.checked = drawCheckedBitmap(plt.Primary(), plt.Lightest()) c.unchecked = drawUncheckedBitmap(plt.Lightest(), plt.Darkest()) if nil == c.checked || nil == c.unchecked { return fmt.Errorf("error creating checkboxes") } return nil } func (c *Checkbox) Handle(ctx Context, ev allg5.Event) { var pressed = c.IsPressed c.ControlBase.Handle(ctx, ev) switch ev.(type) { case *allg5.MouseButtonUpEvent: if !c.Disabled && pressed && c.IsOver { c.Value = !c.Value var onChanged = c.OnChanged if nil != onChanged { onChanged(c.Value) } } } } func (c *Checkbox) DesiredSize(ctx Context) geom.PointF32 { var fonts = ctx.Fonts() var fnt = fonts.Get("default") var w = fnt.TextWidth(c.Text) return geom.PtF32(w+checkboxSize, checkboxSize) } func (c *Checkbox) box() *allg5.Bitmap { if c.Value { return c.checked } return c.unchecked } func (c *Checkbox) Render(ctx Context) { var fonts = ctx.Fonts() var min = c.Bounds.Min var fnt = fonts.Get("default") fnt.Draw(min.X+checkboxSize, min.Y-.67*fnt.Ascent()+.5*checkboxSize, ctx.Palette().Darkest(), allg5.AlignLeft, c.Text) if c.Disabled { var disabled = ctx.Palette().Disabled() c.box().DrawOptions(min.X, min.Y, allg5.DrawOptions{Tint: &disabled}) } else { c.box().Draw(min.X, min.Y) } c.ControlBase.Render(ctx) }