package objects import "git.tebibyte.media/tomo/tomo" import "git.tebibyte.media/tomo/tomo/input" import "git.tebibyte.media/tomo/tomo/event" import "git.tebibyte.media/tomo/objects/layouts" var buttonLayout = layouts.Row { true } var iconButtonLayout = layouts.Row { true } var bothButtonLayout = layouts.Row { false, true } // Button is a clickable button. type Button struct { tomo.ContainerBox label *Label icon *Icon labelActive bool on struct { click event.FuncBroadcaster } } // NewButton creates a new button with the specified text. func NewButton (text string) *Button { box := &Button { ContainerBox: tomo.NewContainerBox(), label: NewLabel(text), } box.SetRole(tomo.R("objects", "Button")) box.label.SetAttr(tomo.AAlign(tomo.AlignMiddle, tomo.AlignMiddle)) box.SetAttr(tomo.ALayout(buttonLayout)) box.SetText(text) box.SetInputMask(true) box.OnButtonDown(box.handleButtonDown) box.OnButtonUp(box.handleButtonUp) box.OnKeyDown(box.handleKeyDown) box.OnKeyUp(box.handleKeyUp) box.SetFocusable(true) return box } // SetText sets the text of the button's label. func (this *Button) SetText (text string) { this.label.SetText(text) if this.labelActive && text == "" { this.Remove(this.label) this.labelActive = false } if !this.labelActive && text != "" { this.Add(this.label) this.labelActive = true } this.applyLayout() } // SetIcon sets an icon for this button. Setting the icon to IconUnknown will // remove it. func (this *Button) SetIcon (id tomo.Icon) { if this.icon != nil { this.Remove(this.icon) } var icon *Icon; if id != tomo.IconUnknown { icon = NewIcon(id, tomo.IconSizeSmall) } this.icon = icon if this.icon != nil { this.Insert(this.icon, this.label) } this.applyLayout() } // OnClick specifies a function to be called when the button is clicked. func (this *Button) OnClick (callback func ()) event.Cookie { return this.on.click.Connect(callback) } func (this *Button) applyLayout () { if this.labelActive && this.icon == nil { this.SetAttr(tomo.ALayout(buttonLayout)) } else if !this.labelActive && this.icon != nil { this.SetAttr(tomo.ALayout(iconButtonLayout)) } else { this.SetAttr(tomo.ALayout(bothButtonLayout)) } } func (this *Button) handleKeyDown (key input.Key, numberPad bool) bool { if key != input.KeyEnter && key != input.Key(' ') { return false } return true } func (this *Button) handleKeyUp (key input.Key, numberPad bool) bool { if key != input.KeyEnter && key != input.Key(' ') { return false } this.on.click.Broadcast() return true } func (this *Button) handleButtonDown (button input.Button) bool { if button != input.ButtonLeft { return false } return true } func (this *Button) handleButtonUp (button input.Button) bool { if button != input.ButtonLeft { return false } if this.Window().MousePosition().In(this.Bounds()) { this.on.click.Broadcast() } return true }