From 343187c1b24ec812aa07247fd7348416b6fd3996 Mon Sep 17 00:00:00 2001 From: yogeshprasad098 Date: Wed, 25 Nov 2026 18:23:47 -0800 Subject: [PATCH] fix(app): stop drawing windows that are closed or hidden A closed dashboard kept its views alive, and their looping animations (pulsing dots, moving power lines) and rolling numbers went on drawing it off screen. The app sat at around half a CPU core with no window open, and the same work on the main thread made scrolling lag. Closing the dashboard or the setup window now drops its contents. The looping animations run from a 30 fps clock that pauses while the window is hidden, covered or behind another app, and numbers roll only while the window is on screen. The menu bar item reads a small value that changes only when its ring or percentage does, instead of redrawing every second, and pointing at a card redraws only its light. Co-Authored-By: Claude Opus 5.5 --- App/AppModel.swift | 21 ++++++-- App/ChargectlApp.swift | 2 +- App/Dashboard/DashboardView.swift | 53 +++++++++++------- App/Dashboard/OverviewPage.swift | 38 +++++++++---- App/Design/DesignSystem.swift | 90 +++++++++++++++++++------------ App/Design/WindowContent.swift | 71 ++++++++++++++++++++++++ App/MenuBar/MenuBarLabel.swift | 45 ++++++++++++---- App/Welcome/WelcomeView.swift | 22 ++++---- CHANGELOG.md | 11 ++++ 9 files changed, 267 insertions(+), 86 deletions(-) create mode 100644 App/Design/WindowContent.swift diff --git a/App/AppModel.swift b/App/AppModel.swift index 1dcddcd..73e2811 100644 --- a/App/AppModel.swift +++ b/App/AppModel.swift @@ -43,10 +43,19 @@ final class AppModel { "com.apphousekitchen.aldente": "AlDente", ] - private(set) var battery: BatterySnapshot? + private(set) var battery: BatterySnapshot? { + didSet { updateMenuBarItem() } + } private(set) var batteryError: String? - private(set) var status: DaemonStatus? - private(set) var service = ServiceState.checking + private(set) var status: DaemonStatus? { + didSet { updateMenuBarItem() } + } + private(set) var service = ServiceState.checking { + didSet { updateMenuBarItem() } + } + /// What the menu bar item shows. It changes far less often than the readings it comes from, + /// and the item redraws only when it does. + private(set) var menuBarItem = MenuBarItem() private(set) var history: [HistorySample] = [] private(set) var logs: [LogEntry] = [] /// One point a day, for the long-term health chart. @@ -112,10 +121,16 @@ final class AppModel { self.macOSLimit = macOSLimit smoothedCurrent = battery?.current isPreview = true + updateMenuBarItem() } #endif var settings: ChargeSettings? { status?.settings } + + private func updateMenuBarItem() { + let item = MenuBarItem(model: self) + if item != menuBarItem { menuBarItem = item } + } var isControllable: Bool { service == .running && status?.adapterKey != nil } /// macOS's own charge limit is running the Mac on battery while Chargectl has the charger diff --git a/App/ChargectlApp.swift b/App/ChargectlApp.swift index aa99170..24f8ccf 100644 --- a/App/ChargectlApp.swift +++ b/App/ChargectlApp.swift @@ -25,7 +25,7 @@ struct ChargectlApp: App { var body: some Scene { MenuBarExtra(isInserted: $showInMenuBar) { - MenuContent(model: model) + WindowContent(dropsContentWhenClosed: false) { MenuContent(model: model) } } label: { MenuBarLabel(model: model) } diff --git a/App/Dashboard/DashboardView.swift b/App/Dashboard/DashboardView.swift index 1d2f8ba..70db10d 100644 --- a/App/Dashboard/DashboardView.swift +++ b/App/Dashboard/DashboardView.swift @@ -32,17 +32,20 @@ struct DashboardView: View { } var body: some View { - HStack(spacing: 0) { - Sidebar(model: model, page: $page) - VStack(alignment: .leading, spacing: 0) { - toolbar - NoticeStack(model: model, includeService: page == .overview) - content - .frame(maxWidth: .infinity, maxHeight: .infinity) - .id(page) + WindowContent { + HStack(spacing: 0) { + Sidebar(model: model, page: $page) + VStack(alignment: .leading, spacing: 0) { + toolbar + NoticeStack(model: model, includeService: page == .overview) + content + .frame(maxWidth: .infinity, maxHeight: .infinity) + .id(page) + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) } - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) } + .frame(maxWidth: .infinity, maxHeight: .infinity) .background { ZStack { Theme.window @@ -236,11 +239,16 @@ private struct HelperFooter: View { } } -/// A status dot with a slow ring that pings outwards. +/// A status dot with a slow ring that pings outwards. The ring is drawn from the clock at 30 +/// frames a second, and holds still while the window is off screen or another app is in front: +/// every frame redraws the whole window. struct PulseDot: View { var color: Color = Theme.accent - @State private var ping = false @Environment(\.accessibilityReduceMotion) private var reduceMotion + @Environment(\.isOnScreen) private var isOnScreen + @Environment(\.appearsActive) private var appearsActive + + private static let period = 2.4 var body: some View { Circle() @@ -248,15 +256,20 @@ struct PulseDot: View { .frame(width: 7, height: 7) .shadow(color: color.opacity(0.7), radius: 4) .background { - Circle() - .stroke(color, lineWidth: 1.5) - .frame(width: 13, height: 13) - .scaleEffect(ping ? 1.6 : 0.6) - .opacity(ping ? 0 : 0.5) - } - .onAppear { - guard !reduceMotion else { return } - withAnimation(.easeOut(duration: 2.4).repeatForever(autoreverses: false)) { ping = true } + if !reduceMotion { + TimelineView(.animation(minimumInterval: 1 / 30, paused: !isOnScreen || !appearsActive)) { + context in + let time = context.date.timeIntervalSinceReferenceDate + let progress = time.truncatingRemainder(dividingBy: Self.period) / Self.period + // Ease out: fast at first, settling as it fades. + let eased = 1 - pow(1 - progress, 3) + Circle() + .stroke(color, lineWidth: 1.5) + .frame(width: 13, height: 13) + .scaleEffect(0.6 + eased) + .opacity(0.5 * (1 - eased)) + } + } } .accessibilityHidden(true) } diff --git a/App/Dashboard/OverviewPage.swift b/App/Dashboard/OverviewPage.swift index 699f138..bdf3158 100644 --- a/App/Dashboard/OverviewPage.swift +++ b/App/Dashboard/OverviewPage.swift @@ -708,6 +708,30 @@ private struct HealthCell: View { } } +/// Dashes travelling along a wire, drawn from the clock at 30 frames a second. They stand still +/// with Reduce Motion, while the window is off screen and while another app is in front. +private struct FlowingDashes: View { + let path: Path + let color: Color + @Environment(\.accessibilityReduceMotion) private var reduceMotion + @Environment(\.isOnScreen) private var isOnScreen + @Environment(\.appearsActive) private var appearsActive + + private static let period = 1.2 + /// One dash and its gap. + private static let length: CGFloat = 18 + + var body: some View { + TimelineView(.animation(minimumInterval: 1 / 30, paused: reduceMotion || !isOnScreen || !appearsActive)) { + context in + let time = context.date.timeIntervalSinceReferenceDate + let phase = + reduceMotion ? 0 : -Self.length * time.truncatingRemainder(dividingBy: Self.period) / Self.period + path.stroke(color, style: StrokeStyle(lineWidth: 2, lineCap: .round, dash: [6, 12], dashPhase: phase)) + } + } +} + /// Charger on the left, Mac and battery on the right, with power travelling along the wires. private struct PowerFlow: View { let charger: Double @@ -715,8 +739,6 @@ private struct PowerFlow: View { let battery: Double let pluggedIn: Bool let wallCut: Bool - @State private var phase: CGFloat = 0 - @Environment(\.accessibilityReduceMotion) private var reduceMotion var body: some View { GeometryReader { geometry in @@ -747,10 +769,6 @@ private struct PowerFlow: View { .position(x: size.width - 70, y: size.height - 30) } } - .onAppear { - guard !reduceMotion else { return } - withAnimation(.linear(duration: 1.2).repeatForever(autoreverses: false)) { phase = -18 } - } } private func wire(from: CGPoint, to: CGPoint, active: Bool, color: Color, bend: Bool = false) -> some View { @@ -768,10 +786,10 @@ private struct PowerFlow: View { return ZStack { path.stroke(Theme.lineStrong, style: StrokeStyle(lineWidth: 2, lineCap: .round)) if active { - path.stroke( - color, style: StrokeStyle(lineWidth: 2, lineCap: .round, dash: [6, 12], dashPhase: phase) - ) - .shadow(color: color.opacity(0.6), radius: 4) + // A soft line under the dashes for the glow: a shadow on the moving dashes would + // be blurred again on every frame. + path.stroke(color.opacity(0.18), style: StrokeStyle(lineWidth: 6, lineCap: .round)) + FlowingDashes(path: path, color: color) } } } diff --git a/App/Design/DesignSystem.swift b/App/Design/DesignSystem.swift index da5d7ff..bfbe217 100644 --- a/App/Design/DesignSystem.swift +++ b/App/Design/DesignSystem.swift @@ -43,9 +43,18 @@ extension Theme { extension View { /// Digits roll whenever the value changes, also when the change came from a background - /// refresh rather than an animated action. + /// refresh rather than an animated action. Not while the window is off screen. func rollingNumber(_ value: Value) -> some View { - contentTransition(.numericText()).animation(.smooth(duration: 0.45), value: value) + modifier(RollingNumber(value: value)) + } +} + +private struct RollingNumber: ViewModifier { + let value: Value + @Environment(\.isOnScreen) private var isOnScreen + + func body(content: Content) -> some View { + content.contentTransition(.numericText()).animation(isOnScreen ? .smooth(duration: 0.45) : nil, value: value) } } @@ -58,7 +67,9 @@ struct Panel: View { var spotlight = false var tint: Color? @ViewBuilder var content: Content - @State private var pointer: CGPoint? + /// Only the lights read it, so moving the pointer (or scrolling under it) redraws them and + /// not the card's content. + @State private var hover = PanelHover() @Environment(\.colorScheme) private var scheme var body: some View { @@ -77,20 +88,7 @@ struct Panel: View { ) .clipShape(shape) } - if let pointer { - // A soft light centred on the pointer, inside the card's own frame so it - // has no edges. - GeometryReader { geometry in - RadialGradient( - colors: [Color.primary.opacity(scheme == .dark ? 0.035 : 0.02), .clear], - center: UnitPoint( - x: pointer.x / max(geometry.size.width, 1), - y: pointer.y / max(geometry.size.height, 1)), - startRadius: 0, endRadius: 260) - } - .clipShape(shape) - .allowsHitTesting(false) - } + PointerLight(hover: hover, shape: shape, isEdge: false) } } .overlay { @@ -100,33 +98,59 @@ struct Panel: View { lineWidth: 1 ) .opacity(scheme == .dark ? 1 : 0) - if let pointer { - GeometryReader { geometry in - shape.strokeBorder( - RadialGradient( - colors: [Theme.accent.opacity(0.55), Color.primary.opacity(0.12), .clear], - center: UnitPoint( - x: pointer.x / max(geometry.size.width, 1), - y: pointer.y / max(geometry.size.height, 1)), - startRadius: 0, endRadius: 220), - lineWidth: 1) - } - .allowsHitTesting(false) - } + PointerLight(hover: hover, shape: shape, isEdge: true) } .shadow( color: .black.opacity(scheme == .dark ? 0.12 : 0.05), radius: scheme == .dark ? 1 : 12, y: scheme == .dark ? 1 : 6 ) - .onContinuousHover(coordinateSpace: .local) { phase in + .onContinuousHover(coordinateSpace: .local) { [hover] phase in switch phase { - case .active(let location): pointer = location - case .ended: withAnimation(.easeOut(duration: 0.3)) { pointer = nil } + case .active(let location): hover.pointer = location + case .ended: withAnimation(.easeOut(duration: 0.3)) { hover.pointer = nil } } } } } +/// Where the pointer is over a card, nil when it is elsewhere. +@Observable +final class PanelHover { + var pointer: CGPoint? +} + +/// A soft light centred on the pointer: across the card, or along its edge. +private struct PointerLight: View { + let hover: PanelHover + let shape: S + let isEdge: Bool + @Environment(\.colorScheme) private var scheme + + var body: some View { + if let pointer = hover.pointer { + GeometryReader { geometry in + let center = UnitPoint( + x: pointer.x / max(geometry.size.width, 1), y: pointer.y / max(geometry.size.height, 1)) + if isEdge { + shape.strokeBorder( + RadialGradient( + colors: [Theme.accent.opacity(0.55), Color.primary.opacity(0.12), .clear], center: center, + startRadius: 0, endRadius: 220), + lineWidth: 1) + } else { + // Inside the card's own frame so it has no edges. + RadialGradient( + colors: [Color.primary.opacity(scheme == .dark ? 0.035 : 0.02), .clear], center: center, + startRadius: 0, endRadius: 260 + ) + .clipShape(shape) + } + } + .allowsHitTesting(false) + } + } +} + /// A card's caption: a small icon and a label, with optional content on the right. struct PanelHeader: View { let title: String diff --git a/App/Design/WindowContent.swift b/App/Design/WindowContent.swift new file mode 100644 index 0000000..5b6451d --- /dev/null +++ b/App/Design/WindowContent.swift @@ -0,0 +1,71 @@ +import AppKit +import SwiftUI + +extension EnvironmentValues { + /// False while the window is closed, minimised, on another Space or covered by other windows. + /// Looping animations and rolling numbers stop then, because they would go on drawing. + @Entry var isOnScreen = true +} + +/// A window's content, built only while the window is open and told whether it is on screen. +/// SwiftUI keeps a closed window's views alive, and their animations and once-a-second updates +/// go on drawing it off screen, which kept the app at half a CPU core with no window open. +struct WindowContent: View { + /// Off for the menu bar panel, which sizes itself to its content and so must keep it. + var dropsContentWhenClosed = true + @ViewBuilder var content: Content + @State private var isOpen = true + @State private var isOnScreen = true + + var body: some View { + ZStack { + if isOpen || !dropsContentWhenClosed { + content.environment(\.isOnScreen, isOnScreen) + } + } + .background { + WindowObserver { open, onScreen in + if open != isOpen { isOpen = open } + if onScreen != isOnScreen { isOnScreen = onScreen } + } + } + } +} + +private struct WindowObserver: NSViewRepresentable { + let report: (_ isOpen: Bool, _ isOnScreen: Bool) -> Void + + func makeNSView(context: Context) -> ObserverView { ObserverView() } + + func updateNSView(_ view: ObserverView, context: Context) { view.report = report } + + final class ObserverView: NSView { + var report: ((Bool, Bool) -> Void)? + private var observers: [NSObjectProtocol] = [] + private var isOpen = true + + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + observers.forEach(NotificationCenter.default.removeObserver) + observers = [] + guard let window else { return } + observers = [NSWindow.didChangeOcclusionStateNotification, NSWindow.willCloseNotification].map { name in + NotificationCenter.default.addObserver(forName: name, object: window, queue: .main) { + [weak self] _ in + MainActor.assumeIsolated { self?.windowChanged(name) } + } + } + } + + private func windowChanged(_ name: Notification.Name) { + guard let window else { return } + if name == NSWindow.willCloseNotification { + isOpen = false + } else if window.isVisible { + // A closed window that is shown again comes back through its occlusion state. + isOpen = true + } + report?(isOpen, isOpen && window.occlusionState.contains(.visible)) + } + } +} diff --git a/App/MenuBar/MenuBarLabel.swift b/App/MenuBar/MenuBarLabel.swift index f502ce2..0ddfd0f 100644 --- a/App/MenuBar/MenuBarLabel.swift +++ b/App/MenuBar/MenuBarLabel.swift @@ -7,18 +7,42 @@ struct MenuBarLabel: View { @Environment(\.openWindow) private var openWindow var body: some View { - let percent = model.battery?.percent + // Reads only menuBarItem: macOS redraws the item, shadow and all, on every change, and + // the battery readings behind it change every second. + let item = model.menuBarItem HStack(spacing: 4) { - Image(nsImage: RingIcon.image(for: model)) - if showPercentage, let percent { + Image(nsImage: RingIcon.image(for: item)) + if showPercentage, let percent = item.percent { Text("\(percent)%") } } - .accessibilityLabel(percent.map { "Battery \($0) percent, \(model.activitySummary)" } ?? "Chargectl") + .accessibilityLabel(item.percent.map { "Battery \($0) percent, \(item.summary)" } ?? "Chargectl") .onAppear { Dashboard.openWindow = openWindow } } } +/// What the menu bar item shows: the ring and the charge. +struct MenuBarItem: Equatable { + var percent: Int? + /// Where the ring's track ends, 0…1; nil draws the whole ring. + var limit: Double? + var glyph = RingIcon.Glyph.attention + /// The helper isn't running. + var isDashed = true + var summary = "" + + init() {} + + init(model: AppModel) { + percent = model.battery?.percent + summary = model.activitySummary + guard model.service == .running, let status = model.status else { return } + limit = status.settings.isEnabled ? Double(status.settings.limit) / 100 : nil + glyph = RingIcon.glyph(for: status.activity) + isDashed = false + } +} + /// The menu bar icon: a ring that fills clockwise from the top. Its track ends at the charge /// limit, so a closed ring means the battery is held there, and a small glyph in the middle says /// what is happening. Template image, so it follows the menu bar tint. @@ -32,12 +56,13 @@ enum RingIcon { } static func image(for model: AppModel, size: CGFloat = 16) -> NSImage { - let fraction = Double(model.battery?.percent ?? 0) / 100 - guard model.service == .running, let status = model.status else { - return image(fraction: fraction, limit: nil, glyph: .attention, dashed: true, size: size) - } - let limit = status.settings.isEnabled ? Double(status.settings.limit) / 100 : nil - return image(fraction: fraction, limit: limit, glyph: glyph(for: status.activity), size: size) + image(for: MenuBarItem(model: model), size: size) + } + + static func image(for item: MenuBarItem, size: CGFloat = 16) -> NSImage { + image( + fraction: Double(item.percent ?? 0) / 100, limit: item.limit, glyph: item.glyph, dashed: item.isDashed, + size: size) } static func glyph(for activity: ChargeActivity) -> Glyph { diff --git a/App/Welcome/WelcomeView.swift b/App/Welcome/WelcomeView.swift index 6bf5385..96ed875 100644 --- a/App/Welcome/WelcomeView.swift +++ b/App/Welcome/WelcomeView.swift @@ -36,15 +36,17 @@ struct WelcomeView: View { } var body: some View { - VStack(spacing: 0) { - // A ZStack, so the page going out and the page coming in overlap instead of stacking. - ZStack(alignment: .top) { - page - .id(step) - .transition(pageTransition) + WindowContent { + VStack(spacing: 0) { + // A ZStack, so the page going out and the page coming in overlap instead of stacking. + ZStack(alignment: .top) { + page + .id(step) + .transition(pageTransition) + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) + footer } - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) - footer } .frame(width: Self.size.width, height: Self.size.height) .background { @@ -599,9 +601,11 @@ private struct Beam: View { let style: Style @Environment(\.accessibilityReduceMotion) private var reduceMotion + @Environment(\.isOnScreen) private var isOnScreen var body: some View { - TimelineView(.animation(paused: style != .flowing || reduceMotion)) { context in + TimelineView(.animation(minimumInterval: 1 / 30, paused: style != .flowing || reduceMotion || !isOnScreen)) { + context in Canvas { canvas, size in let y = size.height / 2 var line = Path() diff --git a/CHANGELOG.md b/CHANGELOG.md index 893809f..6ae1316 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Fixed + +- **Chargectl no longer uses CPU with no window open.** A closed dashboard kept + animating and updating off screen, which held the app at around half a CPU + core all day and made scrolling lag. Closing the dashboard or the setup window + now frees its contents. The moving power lines and pulsing dots pause while + the window is hidden, covered or behind another app, and the numbers only roll + while you can see them. The menu bar item redraws only when its ring or + percentage changes, not every second, and pointing at a card redraws only its + light, not everything inside it. + ## [0.3.0] - 2026-11-25 ### Added