From bfd5774fafb0e3942d418280d53bc6b4bc6a487b Mon Sep 17 00:00:00 2001 From: Hajime Hoshi Date: Thu, 14 Nov 2019 13:07:10 +0900 Subject: [PATCH] graphicsdriver/glfw: Bug fix: CPU was busy when the window is hidden Fixes #982 --- internal/uidriver/glfw/ui.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/internal/uidriver/glfw/ui.go b/internal/uidriver/glfw/ui.go index 47f49422f..8818e40f4 100644 --- a/internal/uidriver/glfw/ui.go +++ b/internal/uidriver/glfw/ui.go @@ -823,6 +823,13 @@ func (u *UserInterface) loop(context driver.UIContext) error { }) }() for { + unfocused := u.window.GetAttrib(glfw.Focused) == glfw.False + + var t1, t2 time.Time + + if unfocused { + t1 = time.Now() + } if err := u.update(context); err != nil { return err } @@ -831,6 +838,19 @@ func (u *UserInterface) loop(context driver.UIContext) error { u.swapBuffers() return nil }) + if unfocused { + t2 = time.Now() + } + + // When a window is not focused, SwapBuffers might return immediately and CPU might be busy. + // Mitigate this by sleeping (#982). + if unfocused { + d := t2.Sub(t1) + const wait = time.Second / 60 + if d < wait { + time.Sleep(wait - d) + } + } } }