Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 26 additions & 7 deletions Sources/App/App.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<AnyCancellable> = []
private var lastIconKey = ""

Expand All @@ -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
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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)
Expand All @@ -125,22 +132,34 @@ 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
window?.makeKeyAndOrderFront(nil)
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() {
Expand Down
43 changes: 38 additions & 5 deletions Sources/App/Model.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import AppKit
import IOKit.ps
import ServiceManagement
import SwiftUI
import UserNotifications
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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<Model>.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()
Expand All @@ -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
Expand All @@ -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
Expand Down
30 changes: 13 additions & 17 deletions Sources/App/Views.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
Expand Down
1 change: 1 addition & 0 deletions Sources/Daemon/Daemon.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading