Allow widgets to specify whether they accept focus

This commit is contained in:
Trevor Slocum 2023-10-23 00:30:39 -07:00
parent f36fbb8087
commit 12d99f9f6d
5 changed files with 23 additions and 14 deletions

8
box.go
View file

@ -12,8 +12,6 @@ type Box struct {
children []Widget
focus bool
sync.Mutex
}
@ -35,12 +33,12 @@ func (b *Box) SetRect(r image.Rectangle) {
b.rect = r
}
func (b *Box) SetFocus(focus bool) {
b.focus = focus
func (b *Box) SetFocus(focus bool) bool {
return false
}
func (b *Box) Focus() bool {
return b.focus
return false
}
func (b *Box) HandleKeyboardEvent(key ebiten.Key, r rune) (handled bool, err error) {

11
game.go
View file

@ -30,13 +30,14 @@ func SetRoot(w Widget) {
}
func SetFocus(w Widget) {
if focusedWidget != nil {
focusedWidget.SetFocus(false)
lastFocused := focusedWidget
if w != nil && !w.SetFocus(true) {
return
}
if lastFocused != nil && lastFocused != w {
lastFocused.SetFocus(false)
}
focusedWidget = w
if w != nil {
w.SetFocus(true)
}
}
func Focused() Widget {

View file

@ -11,6 +11,7 @@ type Input struct {
*Box
Field *messeji.InputField
Cursor string
focus bool
}
func NewInput(prefix string, text string, onSelected func(text string) (handled bool)) *Input {
@ -57,7 +58,7 @@ func (i *Input) SetRect(r image.Rectangle) {
i.Field.SetRect(r)
}
func (i *Input) SetFocus(focus bool) {
func (i *Input) SetFocus(focus bool) bool {
i.focus = focus
var cursor string
@ -65,6 +66,11 @@ func (i *Input) SetFocus(focus bool) {
cursor = i.Cursor
}
i.Field.SetSuffix(cursor)
return true
}
func (i *Input) Focused() bool {
return i.focus
}
func (i *Input) HandleMouse(cursor image.Point, pressed bool, clicked bool) (handled bool, err error) {

View file

@ -26,8 +26,12 @@ func NewText(text string) *Text {
}
}
func (t *Text) SetFocus(focus bool) {
// Do nothing.
func (t *Text) SetFocus(focus bool) bool {
return false
}
func (t *Text) Focus() bool {
return false
}
func (t *Text) Children() []Widget {

View file

@ -9,7 +9,7 @@ import (
type Widget interface {
Rect() image.Rectangle
SetRect(r image.Rectangle)
SetFocus(focus bool)
SetFocus(focus bool) (accept bool)
HandleMouse(cursor image.Point, pressed bool, clicked bool) (handled bool, err error)
HandleKeyboard() (handled bool, err error)
HandleKeyboardEvent(ebiten.Key, rune) (handled bool, err error)