Skip to content

Commit

Permalink
Address crash with empty main menu
Browse files Browse the repository at this point in the history
  • Loading branch information
andydotxyz committed Jun 3, 2020
1 parent 64e5a44 commit 8f9a2c6
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
10 changes: 9 additions & 1 deletion internal/driver/glfw/menu.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,15 @@ import (
)

func buildMenuOverlay(menus *fyne.MainMenu, c fyne.Canvas) fyne.CanvasObject {
if menus.Items[0].Items[len(menus.Items[0].Items)-1].Label != "Quit" { // make sure the first menu always has a quit option
if len(menus.Items) == 0 {
fyne.LogError("Main menu must have at least one child menu", nil)
return nil
}
var firstItem *fyne.MenuItem
if len(menus.Items[0].Items) > 0 {
firstItem = menus.Items[0].Items[len(menus.Items[0].Items)-1]
}
if firstItem == nil || firstItem.Label != "Quit" { // make sure the first menu always has a quit option
quitItem := fyne.NewMenuItem("Quit", func() {
fyne.CurrentApp().Quit()
})
Expand Down
33 changes: 33 additions & 0 deletions internal/driver/glfw/menu_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package glfw

import (
"testing"

"fyne.io/fyne"

"github.com/stretchr/testify/assert"
)

func Test_Menu_Empty(t *testing.T) {
w := createWindow("Menu Test").(*window)
bar := buildMenuOverlay(fyne.NewMainMenu(), w.canvas)
assert.Nil(t, bar) // no bar but does not crash
}

func Test_Menu_AddsQuit(t *testing.T) {
w := createWindow("Menu Test").(*window)
mainMenu := fyne.NewMainMenu(fyne.NewMenu("File"))
bar := buildMenuOverlay(mainMenu, w.canvas)
assert.NotNil(t, bar)
assert.Equal(t, 1, len(mainMenu.Items))
assert.Equal(t, 2, len(mainMenu.Items[0].Items)) // separator+quit inserted
}

func Test_Menu_LeaveQuit(t *testing.T) {
w := createWindow("Menu Test").(*window)
mainMenu := fyne.NewMainMenu(fyne.NewMenu("File", fyne.NewMenuItem("Quit", nil)))
bar := buildMenuOverlay(mainMenu, w.canvas)
assert.NotNil(t, bar)
assert.Equal(t, 1, len(mainMenu.Items[0].Items)) // no separator added
assert.Nil(t, mainMenu.Items[0].Items[0].Action) // no quit handler added
}

0 comments on commit 8f9a2c6

Please sign in to comment.