1
0
Fork 0
mirror of https://github.com/diamondburned/cchat-gtk.git synced 2024-11-01 03:54:16 +00:00
cchat-gtk/internal/gts/throttler/throttler.go

73 lines
1.2 KiB
Go
Raw Normal View History

package throttler
import (
"time"
"github.com/gotk3/gotk3/glib"
"github.com/gotk3/gotk3/gtk"
)
const TPS = 15 // tps
type State struct {
throttling bool
ticker <-chan time.Time
settings *gtk.Settings
}
type Connector interface {
gtk.IWidget
Connect(string, interface{}, ...interface{}) (glib.SignalHandle, error)
}
2020-07-16 05:41:21 +00:00
func Bind(app *gtk.Application) *State {
var settings, _ = gtk.SettingsGetDefault()
var s = State{
settings: settings,
ticker: time.Tick(time.Second / TPS),
}
2020-07-16 05:41:21 +00:00
app.Connect("window-added", func(app *gtk.Application, w *gtk.Window) {
s.Connect(w)
})
return &s
}
2020-07-16 05:41:21 +00:00
func (s *State) Connect(c Connector) {
c.Connect("focus-out-event", s.Start)
c.Connect("focus-in-event", s.Stop)
}
func (s *State) Start() {
if s.throttling {
return
}
s.throttling = true
s.settings.SetProperty("gtk-enable-animations", false)
glib.IdleAdd(func() bool {
// Throttle.
<-s.ticker
// If we're no longer throttling, then stop the ticker and remove this
// callback from the loop.
if !s.throttling {
return false
}
// Keep calling this same callback.
return true
})
}
func (s *State) Stop() {
if !s.throttling {
return
}
s.throttling = false
s.settings.SetProperty("gtk-enable-animations", true)
}