From 2f5c1db63c55173d15a7ab17a9b75564fabd3648 Mon Sep 17 00:00:00 2001 From: Markus Ongyerth Date: Wed, 13 Jun 2018 07:00:57 +0200 Subject: [PATCH] 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 --- lib/ui/tab.go | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/lib/ui/tab.go b/lib/ui/tab.go index f18b0ac..8f08978 100644 --- a/lib/ui/tab.go +++ b/lib/ui/tab.go @@ -40,14 +40,13 @@ 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.onInvalidateContent != nil { - tabs.onInvalidateContent(tabs.TabContent) - } - } - return + if tabs.Selected >= len(tabs.Tabs) { + return + } + + if tabs.Tabs[tabs.Selected].Content == d { + if tabs.onInvalidateContent != nil { + tabs.onInvalidateContent(tabs.TabContent) } } } @@ -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) }