Throttle resize event callbacks

This commit is contained in:
Trevor Slocum 2020-01-01 08:15:11 -08:00
parent 2e5eb3f5a4
commit 004751ce25
1 changed files with 31 additions and 0 deletions

View File

@ -2,6 +2,7 @@ package cview
import (
"sync"
"time"
"github.com/gdamore/tcell"
)
@ -9,6 +10,9 @@ import (
// The size of the event/update/redraw channels.
const queueSize = 100
// The minimum duration between resize event callbacks.
const ResizeEventThrottle = 200 * time.Millisecond
// Application represents the top node of an application.
//
// It is not strictly required to use this class as none of the other classes
@ -43,6 +47,12 @@ type Application struct {
// be forwarded).
inputCapture func(event *tcell.EventKey) *tcell.EventKey
// Time a resize event was last processed.
lastResize time.Time
// Timer limiting how quickly resize events are processed.
throttleResize *time.Timer
// An optional callback function which is invoked when the application's
// window is initialized, and when the application's window size changes.
afterResize func(screen tcell.Screen)
@ -242,10 +252,31 @@ EventLoop:
}
}
case *tcell.EventResize:
if time.Since(a.lastResize) < ResizeEventThrottle {
// Stop timer
if a.throttleResize != nil && !a.throttleResize.Stop() {
select {
case <-a.throttleResize.C:
default:
}
}
event := event // Capture
// Start timer
a.throttleResize = time.AfterFunc(ResizeEventThrottle, func() {
a.events <- event
})
continue
}
a.RLock()
screen := a.screen
a.RUnlock()
a.lastResize = time.Now()
// Call afterResize handler if there is one.
if a.afterResize != nil {
a.afterResize(screen)