From 56c6b459561c0a386412b91547e7475be51f5088 Mon Sep 17 00:00:00 2001 From: Arshd Wani <271769832+arshdwani@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:31:14 +0530 Subject: [PATCH] Stop the hidden panel draining the battery; fix the window crash The popover's SwiftUI views stayed alive after it closed, and the Energy tab's 30 fps flow-arrow animation kept laying out the whole hidden panel: about 18% CPU around the clock on battery. The panel is now built on open and released on close. The arrows are static: animating them made the popover re-measure the panel every frame (about 20% CPU while open, now 1%). While the panel is closed the app polls every 20 s instead of 3 s, picks up battery changes from power source notifications, and skips pmset, system_profiler and history, which only the panel shows. Opening the window (relaunching the app, or the notch fallback) crashed on macOS 26: preferredContentSize sizing in an NSWindow loops AppKit's constraint pass. Windows now size from the view's bounds. The daemon's 5 s timer gets 1 s of tolerance so its wakeups can coalesce. --- Sources/App/App.swift | 33 ++++++++++++++++++++++------ Sources/App/Model.swift | 43 ++++++++++++++++++++++++++++++++----- Sources/App/Views.swift | 30 +++++++++++--------------- Sources/Daemon/Daemon.swift | 1 + 4 files changed, 78 insertions(+), 29 deletions(-) diff --git a/Sources/App/App.swift b/Sources/App/App.swift index 3156c35..a5ae8ad 100644 --- a/Sources/App/App.swift +++ b/Sources/App/App.swift @@ -21,6 +21,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSW private var item: NSStatusItem! private let popover = NSPopover() private var window: NSWindow? + /// Top-left corner of the last closed window, so reopening puts it back there. + private var windowTopLeft: NSPoint? private var cancellables: Set = [] private var lastIconKey = "" @@ -31,7 +33,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSW item.button?.action = #selector(togglePopover) item.button?.imagePosition = .imageTrailing // "80% ▭" like the system battery item - popover.contentViewController = hosting() popover.behavior = .transient popover.animates = true popover.delegate = self @@ -75,9 +76,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSW } } - private func hosting() -> NSViewController { + /// A popover sizes itself from preferredContentSize. A window must size from the + /// view's own bounds instead: there, preferredContentSize re-triggers AppKit's + /// constraint pass until it gives up and crashes the app. + private func hosting(popover: Bool) -> NSViewController { let host = NSHostingController(rootView: PanelView().environmentObject(model)) - host.sizingOptions = .preferredContentSize + host.sizingOptions = popover ? .preferredContentSize : .standardBounds return host } @@ -117,6 +121,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSW popover.performClose(nil) } else { model.panelVisible = true + // The panel's views are built on open and dropped on close (see popoverDidClose), + // because hidden SwiftUI views keep updating, and animating, in the background. + popover.contentViewController = hosting(popover: true) popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY) popover.contentViewController?.view.window?.makeKey() NSApp.activate(ignoringOtherApps: true) @@ -125,12 +132,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSW private func showWindow() { if window == nil { - let w = NSWindow(contentViewController: hosting()) + let w = NSWindow(contentViewController: hosting(popover: false)) w.title = "Dynamo" w.styleMask = [.titled, .closable, .miniaturizable] w.isReleasedWhenClosed = false w.delegate = self - w.center() + if let p = windowTopLeft { w.setFrameTopLeftPoint(p) } else { w.center() } window = w } model.panelVisible = true @@ -138,9 +145,21 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSW NSApp.activate(ignoringOtherApps: true) } - func popoverDidClose(_ notification: Notification) { updatePanelVisible() } + func popoverDidClose(_ notification: Notification) { + if !popover.isShown { popover.contentViewController = nil } + updatePanelVisible() + } + + /// The window is released on close, like the popover's content, and rebuilt on open. func windowWillClose(_ notification: Notification) { - DispatchQueue.main.async { self.updatePanelVisible() } + if let f = window?.frame { windowTopLeft = NSPoint(x: f.minX, y: f.maxY) } + DispatchQueue.main.async { + if self.window?.isVisible == false { + self.window?.delegate = nil + self.window = nil + } + self.updatePanelVisible() + } } private func updatePanelVisible() { diff --git a/Sources/App/Model.swift b/Sources/App/Model.swift index 29eede4..60c13fc 100644 --- a/Sources/App/Model.swift +++ b/Sources/App/Model.swift @@ -1,4 +1,5 @@ import AppKit +import IOKit.ps import ServiceManagement import SwiftUI import UserNotifications @@ -30,8 +31,13 @@ final class Model: ObservableObject { /// Result of the last manual "Check for Updates". @Published var updateCheck = UpdateCheck.idle /// Energy sampling walks every process, so it only runs while someone is looking. + /// Refreshes also slow down while the panel is closed (see startTimer). var panelVisible = false { - didSet { if panelVisible && !oldValue { refresh() } } + didSet { + guard panelVisible != oldValue else { return } + startTimer() + if panelVisible { refresh() } + } } /// Hides identifying details (battery serial) for screenshots. var redacted = false @@ -53,9 +59,8 @@ final class Model: ObservableObject { restoreKnownUpdate() refresh() _ = energy.sample() // baseline, so the first look at the panel has real numbers - timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { [weak self] _ in - Task { @MainActor in self?.refresh() } - } + startTimer() + watchPowerSources() observers.append(NotificationCenter.default.addObserver( forName: .NSProcessInfoPowerStateDidChange, object: nil, queue: .main) { [weak self] _ in Task { @MainActor in @@ -66,6 +71,31 @@ final class Model: ObservableObject { }) } + /// Live numbers every 3 s while the panel is open. While it's closed only the menu + /// bar icon needs them and battery changes arrive as notifications, so a slow poll + /// for the daemon's status is enough; it stays well inside DaemonStatus.isFresh's + /// 60 s even with the daemon's 20 s heartbeat. The tolerance lets macOS batch wakeups. + private func startTimer() { + timer?.invalidate() + let interval: TimeInterval = panelVisible ? 3 : 20 + timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in + Task { @MainActor in self?.refresh() } + } + timer?.tolerance = interval / 5 + } + + /// Refreshes as soon as macOS reports a battery change (plugged in, charge level, ...), + /// so the menu bar icon keeps up without polling. + private func watchPowerSources() { + let ctx = Unmanaged.passUnretained(self).toOpaque() + guard let src = IOPSNotificationCreateRunLoopSource({ ctx in + guard let ctx else { return } + let model = Unmanaged.fromOpaque(ctx).takeUnretainedValue() + Task { @MainActor in model.refresh() } + }, ctx)?.takeRetainedValue() else { return } + CFRunLoopAddSource(CFRunLoopGetMain(), src, .defaultMode) + } + func refresh() { guard !frozen else { return } battery = BatteryInfo.read() @@ -76,8 +106,12 @@ final class Model: ObservableObject { if let c = Config.load(), c != config { config = c } if let s = status { notifyIfNeeded(s) } + checkForUpdates() + // The rest only shows in the panel: load it at launch, then only while the panel + // is open (opening it refreshes, which catches up anything that went stale). let now = Date() + guard panelVisible || lastHistoryLoad == .distantPast else { return } // pmset is a process launch, so read it rarely: every 30 s, or right after a change. if now.timeIntervalSince(lastLowPowerRead) > 30 && now.timeIntervalSince(lowPowerRequestedAt) > 6 { lastLowPowerRead = now @@ -93,7 +127,6 @@ final class Model: ObservableObject { await MainActor.run { self.appleHealth = h } } } - checkForUpdates() if now.timeIntervalSince(lastHistoryLoad) > 60 { history = History.load() lastHistoryLoad = now diff --git a/Sources/App/Views.swift b/Sources/App/Views.swift index 9cc6519..fe43b04 100644 --- a/Sources/App/Views.swift +++ b/Sources/App/Views.swift @@ -918,31 +918,27 @@ struct FlowNode: View { } } -/// A dashed line whose dashes travel in the direction power flows. +/// A dashed line with a chevron pointing the way power flows. Deliberately static: +/// animating it made the popover re-measure the whole panel every frame (~20% CPU). struct FlowArrow: View { var active: Bool var forward: Bool var color: Color var body: some View { - TimelineView(.animation(minimumInterval: 1 / 30, paused: !active)) { ctx in - let t = ctx.date.timeIntervalSinceReferenceDate - let phase = CGFloat(t.truncatingRemainder(dividingBy: 0.8) / 0.8) * 8 - ZStack { - Path { p in - p.move(to: CGPoint(x: 2, y: 6)) - p.addLine(to: CGPoint(x: 30, y: 6)) - } - .stroke(active ? color : Color.secondary.opacity(0.3), - style: StrokeStyle(lineWidth: 2, lineCap: .round, dash: [3, 5], - dashPhase: active ? (forward ? -phase : phase) : 0)) - Image(systemName: forward ? "chevron.right" : "chevron.left") - .font(.system(size: 9, weight: .heavy)) - .foregroundStyle(active ? color : Color.secondary.opacity(0.3)) - .offset(x: forward ? 13 : -13) + ZStack { + Path { p in + p.move(to: CGPoint(x: 2, y: 6)) + p.addLine(to: CGPoint(x: 30, y: 6)) } - .frame(width: 32, height: 12) + .stroke(active ? color : Color.secondary.opacity(0.3), + style: StrokeStyle(lineWidth: 2, lineCap: .round, dash: [3, 5])) + Image(systemName: forward ? "chevron.right" : "chevron.left") + .font(.system(size: 9, weight: .heavy)) + .foregroundStyle(active ? color : Color.secondary.opacity(0.3)) + .offset(x: forward ? 13 : -13) } + .frame(width: 32, height: 12) .padding(.bottom, 30) } } diff --git a/Sources/Daemon/Daemon.swift b/Sources/Daemon/Daemon.swift index 8448ae8..703bf32 100644 --- a/Sources/Daemon/Daemon.swift +++ b/Sources/Daemon/Daemon.swift @@ -63,6 +63,7 @@ final class Daemon { registerForSleep() timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { [weak self] _ in self?.tick() } + timer?.tolerance = 1 // lets macOS coalesce the wakeup with others tick() RunLoop.main.run() exit(0)