From 4024b9ac4d6382c5fb4b1179be3c79206de6c307 Mon Sep 17 00:00:00 2001 From: Matthias Grandl <50196894+MatthiasGrandl@users.noreply.github.com> Date: Fri, 3 May 2024 10:35:51 +0200 Subject: [PATCH] gpui: Fix `start_display_link` leading to resource leak on hidden windows (#11289) Release Notes: - N/A While developing [Loungy](https://loungy.app), I noticed that everytime I wake my laptop, Loungy starts consuming 100% CPU. I traced it down to `start_display_link` as there was this error message at the time of wake up: ``` [2024-05-02T05:02:31Z ERROR util] /Users/matthias/zed/crates/gpui/src/platform/mac/window.rs:420: could not create display link, code: -6661 ``` The timeline is this: 1. The application is hidden with `cx.hide()` 2. The system is put to sleep and later woken up 3. `window_did_change_screen` would trigger immediately after wakeup, calling `start_display_link` 4. `start_display_link` fails catastrophically as `DisplayLink::new` starts hogging all the CPU for some reason? 5. throws the error message above 6. Once the window is opened, `window_did_change_occlusion_state` it retriggers `start_display_link` and the CPU issue subsides --- crates/gpui/src/platform/mac/window.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/gpui/src/platform/mac/window.rs b/crates/gpui/src/platform/mac/window.rs index 86d01ba2dc..66bb6bd40f 100644 --- a/crates/gpui/src/platform/mac/window.rs +++ b/crates/gpui/src/platform/mac/window.rs @@ -415,6 +415,15 @@ impl MacWindowState { fn start_display_link(&mut self) { self.stop_display_link(); + unsafe { + if !self + .native_window + .occlusionState() + .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible) + { + return; + } + } let display_id = unsafe { display_id_for_screen(self.native_window.screen()) }; if let Some(mut display_link) = DisplayLink::new(display_id, self.native_view.as_ptr() as *mut c_void, step).log_err()