package ui import ( "fmt" "image/color" "github.com/llgcode/draw2d/draw2dimg" "github.com/llgcode/draw2d/draw2dkit" "opslag.de/schobers/galleg/allegro5" "opslag.de/schobers/geom" ) type CheckboxValueChangedFn func(bool) func drawCheckedBitmap(fill, stroke color.Color) *allegro5.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) *allegro5.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 *allegro5.Bitmap unchecked *allegro5.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 allegro5.Event) { var pressed = c.IsPressed c.ControlBase.Handle(ctx, ev) switch ev.(type) { case *allegro5.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.PointF { var fonts = ctx.Fonts() var fnt = fonts.Get("default") var w = fnt.TextWidth(c.Text) return geom.PtF(float64(w+checkboxSize+leftMargin), checkboxSize) } func (c *Checkbox) box() *allegro5.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.To32() var fnt = fonts.Get("default") fnt.Draw(min.X+checkboxSize, min.Y-.67*fnt.Ascent()+.5*checkboxSize, ctx.Palette().Darkest(), allegro5.AlignLeft, c.Text) if c.Disabled { var disabled = ctx.Palette().Disabled() c.box().DrawOptions(min.X, min.Y, allegro5.DrawOptions{Tint: &disabled}) } else { c.box().Draw(min.X, min.Y) } c.ControlBase.Render(ctx) }