Skip to content

Commit

Permalink
fyne-ioGH-2306: use lazy initialization of button
Browse files Browse the repository at this point in the history
Since the ToolbarAction can also be created
without the constructor, the pointer to the
button could be nil.
  • Loading branch information
maruu committed Jan 19, 2024
1 parent a701d5f commit d9f4e9d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
22 changes: 17 additions & 5 deletions widget/toolbar.go
Expand Up @@ -22,8 +22,16 @@ type ToolbarAction struct {

// ToolbarObject gets a button to render this ToolbarAction
func (t *ToolbarAction) ToolbarObject() fyne.CanvasObject {
t.button.Icon = t.Icon
t.button.OnTapped = t.OnActivated
if t.button == nil {
// lazy initialization of the button, when the ToolbarAction
// has not been created via the constructor
t.button = createToolbarActionButton(t.Icon, t.OnActivated)
} else {
// synchronize properties
t.button.Icon = t.Icon
t.button.OnTapped = t.OnActivated
}

return t.button
}

Expand Down Expand Up @@ -56,12 +64,16 @@ func (t *ToolbarAction) Disabled() bool {
return t.button.Disabled()
}

// NewToolbarAction returns a new push button style ToolbarItem
func NewToolbarAction(icon fyne.Resource, onActivated func()) *ToolbarAction {
func createToolbarActionButton(icon fyne.Resource, onActivated func()) *Button {
button := NewButtonWithIcon("", icon, onActivated)
button.Importance = LowImportance

return &ToolbarAction{Icon:icon, OnActivated: onActivated, button: button}
return button
}

// NewToolbarAction returns a new push button style ToolbarItem
func NewToolbarAction(icon fyne.Resource, onActivated func()) *ToolbarAction {
return &ToolbarAction{Icon: icon, OnActivated: onActivated, button: createToolbarActionButton(icon, onActivated)}
}

// ToolbarSpacer is a blank, stretchable space for a toolbar.
Expand Down
9 changes: 8 additions & 1 deletion widget/toolbar_test.go
Expand Up @@ -112,7 +112,7 @@ func TestToolbarAction_UpdateOnActivated(t *testing.T) {
activated := false

testIcon := theme.InfoIcon()
toolbarAction := NewToolbarAction(testIcon, func() {activated = true})
toolbarAction := NewToolbarAction(testIcon, func() { activated = true })

test.Tap(toolbarAction.ToolbarObject().(*Button))

Expand All @@ -126,3 +126,10 @@ func TestToolbarAction_UpdateOnActivated(t *testing.T) {

assert.False(t, activated)
}

func TestToolbarAction_DefaultCreation(t *testing.T) {
testIcon := theme.InfoIcon()
toolbarAction := ToolbarAction{Icon: testIcon}
obj := toolbarAction.ToolbarObject()
assert.Equal(t, testIcon, obj.(*Button).Icon)
}

0 comments on commit d9f4e9d

Please sign in to comment.