diff --git a/Sources/App/App.swift b/Sources/App/App.swift index a5ae8ad..fe46411 100644 --- a/Sources/App/App.swift +++ b/Sources/App/App.swift @@ -80,7 +80,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSW /// 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)) + // Fit on the screen below the menu bar, leaving room for the popover's arrow + // or the window's title bar. + let screen = (popover ? item.button?.window?.screen : nil) ?? NSScreen.main + let maxHeight = (screen?.visibleFrame.height ?? 800) - 40 + let host = NSHostingController(rootView: PanelView(maxHeight: maxHeight).environmentObject(model)) host.sizingOptions = popover ? .preferredContentSize : .standardBounds return host } diff --git a/Sources/App/EnergyMonitor.swift b/Sources/App/EnergyMonitor.swift index d510e10..8f8b810 100644 --- a/Sources/App/EnergyMonitor.swift +++ b/Sources/App/EnergyMonitor.swift @@ -21,6 +21,8 @@ final class EnergyMonitor { private var last: [pid_t: Sample] = [:] private var lastTime: UInt64 = 0 private var paths: [pid_t: String] = [:] + /// Display names by key: looking them up for every app took most of each sample. + private var names: [String: String] = [:] private var smoothed: [String: (watts: Double, cpu: Double)] = [:] private let timebase: Double = { var tb = mach_timebase_info() @@ -62,16 +64,24 @@ final class EnergyMonitor { if v.0 > 0.005 || perApp[key] != nil { next[key] = v } } smoothed = next + names = names.filter { smoothed[$0.key] != nil } return smoothed.map { key, v in - let isApp = key.hasSuffix(".app") - let name = isApp ? FileManager.default.displayName(atPath: key).replacingOccurrences(of: ".app", with: "") - : (key as NSString).lastPathComponent - return AppEnergy(id: key, name: name, bundlePath: isApp ? key : nil, watts: v.watts, cpuPercent: v.cpu) + AppEnergy(id: key, name: name(for: key), bundlePath: key.hasSuffix(".app") ? key : nil, + watts: v.watts, cpuPercent: v.cpu) } .sorted { $0.watts > $1.watts } } + private func name(for key: String) -> String { + if let n = names[key] { return n } + let n = key.hasSuffix(".app") + ? FileManager.default.displayName(atPath: key).replacingOccurrences(of: ".app", with: "") + : (key as NSString).lastPathComponent + names[key] = n + return n + } + private func appKey(for pid: pid_t) -> String { if let p = paths[pid] { return p } var buf = [CChar](repeating: 0, count: Int(MAXPATHLEN) * 4) diff --git a/Sources/App/Model.swift b/Sources/App/Model.swift index 60c13fc..d358661 100644 --- a/Sources/App/Model.swift +++ b/Sources/App/Model.swift @@ -291,7 +291,7 @@ final class Model: ObservableObject { return cfg.enabled ? "Will charge to \(cfg.limit)% when plugged in" : "Calculating time remaining…" case .charging: return "Up to \(cfg.limit)%" case .holding: return "Charging paused at \(cfg.limit)%" - case .sailing: return "Charging resumes below \(cfg.limit - cfg.sailing)%" + case .sailing: return "Charging resumes at \(cfg.limit - cfg.sailing)%" case .heatPaused, .discharging, .calibrating, .topUp: return status?.reason ?? "" case .noConfig: return "Run install.sh to finish setup" } diff --git a/Sources/App/Views.swift b/Sources/App/Views.swift index fe43b04..857acc8 100644 --- a/Sources/App/Views.swift +++ b/Sources/App/Views.swift @@ -5,9 +5,12 @@ import SwiftUI struct PanelView: View { @EnvironmentObject var model: Model + /// The screen's free height. A taller panel (say, Settings expanded) would run off + /// the bottom of the screen, so past this the tab scrolls between header and footer. + var maxHeight: CGFloat = .infinity var body: some View { - VStack(alignment: .leading, spacing: 12) { + PanelStack(spacing: 12, maxHeight: maxHeight - 28) { // 28: the padding if model.iconHidden { Notice(text: "Your menu bar icon is hidden behind the notch. ⌘-drag other icons off the " + "menu bar to make room. Opening Dynamo again always shows this window.", @@ -16,7 +19,7 @@ struct PanelView: View { if let update = model.availableUpdate { UpdateBanner(release: update) } Header() TabBar() - Group { + let tab = Group { switch model.tab { case 1: HealthTab() case 2: HistoryTab() @@ -25,6 +28,13 @@ struct PanelView: View { } } .transition(.opacity) + if maxHeight < .infinity { + ScrollView { tab } + .bounceOnlyWhenScrollable() + .layoutValue(key: Scrolls.self, value: true) + } else { + tab // uncapped (snapshots): ImageRenderer can't draw a ScrollView's content + } Footer() } .padding(14) @@ -32,6 +42,50 @@ struct PanelView: View { } } +/// Stacks the panel's sections like a leading VStack, each at its natural height, except +/// that the one marked `Scrolls` gives up height once the total would pass `maxHeight`. +/// A VStack would let that ScrollView shrink at will, and the window, which sizes to +/// the panel's minimum, would open squashed; here the panel's height is always exact. +struct PanelStack: Layout { + var spacing: CGFloat + var maxHeight: CGFloat + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + let width = proposal.width + ?? subviews.map { $0.sizeThatFits(.unspecified).width }.max() ?? 0 + let heights = heights(width: width, subviews) + return CGSize(width: width, height: heights.reduce(0, +) + spacing * CGFloat(max(0, heights.count - 1))) + } + + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + var y = bounds.minY + for (view, height) in zip(subviews, heights(width: bounds.width, subviews)) { + view.place(at: CGPoint(x: bounds.minX, y: y), proposal: ProposedViewSize(width: bounds.width, height: height)) + y += height + spacing + } + } + + private func heights(width: CGFloat, _ subviews: Subviews) -> [CGFloat] { + var heights = subviews.map { $0.sizeThatFits(ProposedViewSize(width: width, height: nil)).height } + if let i = subviews.firstIndex(where: { $0[Scrolls.self] }) { + let rest = heights.reduce(0, +) - heights[i] + spacing * CGFloat(heights.count - 1) + heights[i] = max(0, min(heights[i], maxHeight - rest)) + } + return heights + } +} + +private struct Scrolls: LayoutValueKey { + static let defaultValue = false +} + +extension View { + /// The panel usually fits, and then it shouldn't rubber-band under a two-finger swipe. + @ViewBuilder func bounceOnlyWhenScrollable() -> some View { + if #available(macOS 13.3, *) { scrollBounceBehavior(.basedOnSize) } else { self } + } +} + /// "Check for Updates" button with an inline result. struct UpdateCheckRow: View { @EnvironmentObject var model: Model @@ -591,7 +645,7 @@ struct LimitCard: View { VStack(alignment: .leading, spacing: 8) { HStack(alignment: .firstTextBaseline, spacing: 8) { Text("\(shown)%").font(.system(size: 28, weight: .bold, design: .rounded)).monospacedDigit() - Text(shown >= 100 ? "Charges fully" : "Resumes below \(shown - cfg.sailing)%") + Text(shown >= 100 ? "Charges fully" : "Resumes at \(shown - cfg.sailing)%") .font(.callout).foregroundStyle(.secondary) } LimitSlider(value: model.draftLimit ?? Double(cfg.limit)) { v in @@ -773,6 +827,7 @@ struct SettingsCard: View { @AppStorage("settingsOpen") private var open = false @AppStorage("showPercent") private var showPercent = true @AppStorage("notifications") private var notifications = true + @AppStorage("checkUpdates") private var checkUpdates = true var body: some View { let cfg = model.config @@ -813,10 +868,11 @@ struct SettingsCard: View { SettingToggle(title: "Show percentage in menu bar", detail: nil, isOn: $showPercent) SettingToggle(title: "Notify when tasks finish", detail: nil, isOn: $notifications) SettingToggle(title: "Automatic update checks", detail: "Once a day, from GitHub", - isOn: Binding(get: { UserDefaults.standard.object(forKey: "checkUpdates") as? Bool ?? true }, + isOn: Binding(get: { checkUpdates }, set: { v in - UserDefaults.standard.set(v, forKey: "checkUpdates") - if v { model.checkForUpdates(force: true) } + checkUpdates = v + // Off also drops a known update's banner, as at launch. + if v { model.checkForUpdates(force: true) } else { model.availableUpdate = nil } })) UpdateCheckRow() SettingToggle(title: "Launch at login", detail: nil, diff --git a/Sources/Daemon/Daemon.swift b/Sources/Daemon/Daemon.swift index 703bf32..e740d58 100644 --- a/Sources/Daemon/Daemon.swift +++ b/Sources/Daemon/Daemon.swift @@ -87,7 +87,8 @@ final class Daemon { asleepSince = nil } guard let bat = BatteryInfo.read() else { - writeStatus(mode: nil, reason: "Battery unreadable", error: "Could not read AppleSmartBattery") + writeStatus(mode: nil, reason: "Battery unreadable", error: "Could not read AppleSmartBattery", + inhibited: ChargeControl.chargingInhibited, adapterDisabled: ChargeControl.adapterDisabled) return } if History.record(bat, into: &history) { History.save(history) } @@ -136,15 +137,21 @@ final class Daemon { event = (text, Date()) } + /// Each SMC key is read once per tick (a read is a kernel round trip), and again + /// only after a write, so the status reports what the SMC actually took. private func apply(_ d: Decision) { var error: String? + var inhibited = ChargeControl.chargingInhibited + var adapterDisabled = ChargeControl.adapterDisabled do { - if ChargeControl.chargingInhibited != d.inhibitCharging { + if inhibited != d.inhibitCharging { try ChargeControl.setChargingInhibited(d.inhibitCharging) + inhibited = ChargeControl.chargingInhibited log("charging \(d.inhibitCharging ? "inhibited" : "enabled"): \(d.reason)") } - if (ChargeControl.adapterDisabled ?? false) != d.disableAdapter { + if (adapterDisabled ?? false) != d.disableAdapter { try ChargeControl.setAdapterDisabled(d.disableAdapter) + adapterDisabled = ChargeControl.adapterDisabled log("adapter \(d.disableAdapter ? "disabled" : "enabled"): \(d.reason)") } } catch let e { @@ -153,7 +160,7 @@ final class Daemon { } applyLED(green: d.greenLED) setSleepPrevented(d.preventSleep) - writeStatus(mode: d.mode, reason: d.reason, error: error) + writeStatus(mode: d.mode, reason: d.reason, error: error, inhibited: inhibited, adapterDisabled: adapterDisabled) } /// Only touches the LED while overriding it, so macOS keeps control otherwise. @@ -185,10 +192,10 @@ final class Daemon { } } - private func writeStatus(mode: ChargeMode?, reason: String, error: String?) { + private func writeStatus(mode: ChargeMode?, reason: String, error: String?, inhibited: Bool?, adapterDisabled: Bool?) { let s = DaemonStatus(updatedAt: Date(), mode: mode, - chargingInhibited: ChargeControl.chargingInhibited ?? false, - adapterDisabled: ChargeControl.adapterDisabled ?? false, + chargingInhibited: inhibited ?? false, + adapterDisabled: adapterDisabled ?? false, sleepPrevented: assertion != 0, reason: reason, error: error, calibration: state.calibration, diff --git a/Sources/smc.c b/Sources/smc.c index 725fb0f..3d9f4a5 100644 --- a/Sources/smc.c +++ b/Sources/smc.c @@ -64,15 +64,30 @@ void smc_close(void) { conn = 0; } +// A key's size and type never change, so each is looked up once. That halves the +// kernel calls per read; the daemon reads a few keys every tick. Single-threaded use. +#define INFO_CACHE_SIZE 16 +static struct { uint32_t key; SMCKeyInfo info; } info_cache[INFO_CACHE_SIZE]; +static int info_cached = 0; + static int key_info(const char *key, SMCKeyInfo *info) { + uint32_t k = fourcc(key); + for (int i = 0; i < info_cached; i++) { + if (info_cache[i].key == k) { *info = info_cache[i].info; return 0; } + } SMCParam in, out; memset(&in, 0, sizeof in); memset(&out, 0, sizeof out); - in.key = fourcc(key); + in.key = k; in.data8 = SMC_CMD_READ_KEYINFO; int rc = call(&in, &out); if (rc) return rc; *info = out.keyInfo; + if (info_cached < INFO_CACHE_SIZE) { + info_cache[info_cached].key = k; + info_cache[info_cached].info = out.keyInfo; + info_cached++; + } return 0; }