From 46f3b4409f75b2d936dc6f6d54c1249be182b8f9 Mon Sep 17 00:00:00 2001 From: Jordan Baird Date: Wed, 10 Jul 2024 18:33:21 -0600 Subject: [PATCH] Don't cache item images if app isn't frontmost --- Ice/Main/AppState.swift | 33 +++++++++++++++++-------- Ice/MenuBar/MenuBarItemImageCache.swift | 4 +++ Ice/Navigation/AppNavigationState.swift | 1 + 3 files changed, 28 insertions(+), 10 deletions(-) diff --git a/Ice/Main/AppState.swift b/Ice/Main/AppState.swift index 5bd2e3a5..4d9c7b5e 100644 --- a/Ice/Main/AppState.swift +++ b/Ice/Main/AppState.swift @@ -104,6 +104,16 @@ final class AppState: ObservableObject { } .store(in: &c) + NSWorkspace.shared.publisher(for: \.frontmostApplication) + .receive(on: DispatchQueue.main) + .sink { [weak self] frontmostApplication in + guard let self else { + return + } + navigationState.isAppFrontmost = frontmostApplication == .current + } + .store(in: &c) + if let settingsWindow { settingsWindow.publisher(for: \.isVisible) .receive(on: DispatchQueue.main) @@ -116,17 +126,20 @@ final class AppState: ObservableObject { .store(in: &c) } - navigationState.$isSettingsPresented - .receive(on: DispatchQueue.main) - .sink { isPresented in - guard isPresented else { - return - } - Task { - await self.imageCache.updateCacheWithoutChecks(sections: MenuBarSection.Name.allCases) - } + Publishers.Merge( + navigationState.$isAppFrontmost, + navigationState.$isSettingsPresented + ) + .debounce(for: 0.1, scheduler: DispatchQueue.main) + .sink { shouldUpdate in + guard shouldUpdate else { + return } - .store(in: &c) + Task { + await self.imageCache.updateCacheWithoutChecks(sections: MenuBarSection.Name.allCases) + } + } + .store(in: &c) menuBarManager.objectWillChange .sink { [weak self] in diff --git a/Ice/MenuBar/MenuBarItemImageCache.swift b/Ice/MenuBar/MenuBarItemImageCache.swift index 1b769ebc..fce2b00e 100644 --- a/Ice/MenuBar/MenuBarItemImageCache.swift +++ b/Ice/MenuBar/MenuBarItemImageCache.swift @@ -207,6 +207,10 @@ class MenuBarItemImageCache: ObservableObject { } if !appState.navigationState.isIceBarPresented { + guard appState.navigationState.isAppFrontmost else { + Logger.imageCache.debug("Skipping image cache as Ice Bar not visible, app not frontmost") + return + } guard appState.navigationState.isSettingsPresented else { Logger.imageCache.debug("Skipping image cache as Ice Bar not visible, Settings not visible") return diff --git a/Ice/Navigation/AppNavigationState.swift b/Ice/Navigation/AppNavigationState.swift index 51fe1127..9833195e 100644 --- a/Ice/Navigation/AppNavigationState.swift +++ b/Ice/Navigation/AppNavigationState.swift @@ -8,6 +8,7 @@ import Combine /// The model for app-wide navigation. @MainActor final class AppNavigationState: ObservableObject { + @Published var isAppFrontmost = false @Published var isSettingsPresented = false @Published var isIceBarPresented = false @Published var settingsNavigationIdentifier: SettingsNavigationIdentifier = .general