refactor lib/ui/tab to ensure staying in bounds

Fix a few potential out of bounds by placing proper checks, which should
be relevant if all tabs are removed for some reason.

Also avoid iterating all tabs in the invalidate handler, since we are
only interested in whether it's the selected tab either way
This commit is contained in:
Markus Ongyerth 2018-06-13 07:00:57 +02:00 committed by Drew DeVault
parent 1265d9cff8
commit 2f5c1db63c

View file

@ -40,16 +40,15 @@ func (tabs *Tabs) Add(content Drawable, name string) {
}
func (tabs *Tabs) invalidateChild(d Drawable) {
for i, tab := range tabs.Tabs {
if tab.Content == d {
if i == tabs.Selected {
if tabs.Selected >= len(tabs.Tabs) {
return
}
if tabs.Tabs[tabs.Selected].Content == d {
if tabs.onInvalidateContent != nil {
tabs.onInvalidateContent(tabs.TabContent)
}
}
return
}
}
}
func (tabs *Tabs) Remove(content Drawable) {
@ -59,10 +58,18 @@ func (tabs *Tabs) Remove(content Drawable) {
break
}
}
/* Force the selected index into the existing range */
if tabs.Selected >= len(tabs.Tabs) {
tabs.Select(len(tabs.Tabs) - 1)
}
tabs.TabStrip.Invalidate()
}
func (tabs *Tabs) Select(index int) {
if tabs.Selected >= len(tabs.Tabs) {
panic("Tried to set tab index to a non-existing element")
}
if tabs.Selected != index {
tabs.Selected = index
tabs.TabStrip.Invalidate()
@ -101,6 +108,12 @@ func (strip *TabStrip) OnInvalidate(onInvalidate func(d Drawable)) {
}
func (content *TabContent) Draw(ctx *Context) {
if content.Selected >= len(content.Tabs) {
width := ctx.Width()
height := ctx.Height()
ctx.Fill(0, 0, width, height, ' ', tcell.StyleDefault)
}
tab := content.Tabs[content.Selected]
tab.Content.Draw(ctx)
}