From 639ad64f086f094bec6dd311cc175af9c0df949e Mon Sep 17 00:00:00 2001 From: Nick Wolff Date: Tue, 20 Oct 2026 10:27:10 -0400 Subject: [PATCH 1/3] feat(keepawake): add low-battery cutoff - Turn off Keep Awake at or below a cutoff while on battery - Refuse to turn it back on until charging or above the cutoff - Persist the cutoff, on by default at 20%, clamped to 5-50% --- .../Sources/BarometryKit/KeepAwake.swift | 51 ++++++++++++- .../BarometryKit/Settings/Preferences.swift | 13 ++++ .../BarometryKitTests/KeepAwakeTests.swift | 73 +++++++++++++++++++ .../BarometryKitTests/PreferencesTests.swift | 11 +++ 4 files changed, 146 insertions(+), 2 deletions(-) diff --git a/Packages/BarometryKit/Sources/BarometryKit/KeepAwake.swift b/Packages/BarometryKit/Sources/BarometryKit/KeepAwake.swift index ac801be..b49d8fd 100644 --- a/Packages/BarometryKit/Sources/BarometryKit/KeepAwake.swift +++ b/Packages/BarometryKit/Sources/BarometryKit/KeepAwake.swift @@ -6,7 +6,8 @@ import Observation /// Keeps the display, and with it the system, from idle sleep while enabled, like /// `caffeinate -d`, and optionally nudges the cursor so apps watching for user activity -/// see some. Starts disabled each launch. +/// see some. Starts disabled each launch, and stays off while the battery is at or below +/// `lowBatteryCutoff`. @MainActor @Observable public final class KeepAwake { @@ -23,6 +24,24 @@ public final class KeepAwake { } } + /// Whether the battery is at or below `lowBatteryCutoff`, which keeps Keep Awake off. + public private(set) var isBlockedByLowBattery = false + + /// Charge at or below which Keep Awake turns off and can't be turned on while on battery + /// power, or nil to ignore the battery. + @ObservationIgnored public var lowBatteryCutoff: LowBatteryCutoff? { + didSet { + if lowBatteryCutoff != oldValue { applyLowBatteryCutoff() } + } + } + + /// The latest reading, or nil on Macs without a battery. + @ObservationIgnored public var battery: BatterySample? { + didSet { + if battery != oldValue { applyLowBatteryCutoff() } + } + } + @ObservationIgnored private var assertion: PowerAssertion? @ObservationIgnored private var cursorNudger: CursorNudger? @@ -32,14 +51,21 @@ public final class KeepAwake { setEnabled(!isEnabled) } - /// Stays disabled if macOS refuses the assertion. + /// Stays disabled if macOS refuses the assertion or the battery is too low. public func setEnabled(_ enabled: Bool) { + let enabled = enabled && !isBlockedByLowBattery guard enabled != isEnabled else { return } assertion = enabled ? PowerAssertion(type: Self.assertionType, name: Self.assertionName) : nil isEnabled = assertion != nil updateCursorNudger() } + private func applyLowBatteryCutoff() { + let isBlocked = lowBatteryCutoff?.isReached(by: battery) ?? false + if isBlocked != isBlockedByLowBattery { isBlockedByLowBattery = isBlocked } + if isBlocked { setEnabled(false) } + } + private func updateCursorNudger() { if isEnabled, let interval = cursorNudgeInterval { cursorNudger = CursorNudger(every: interval.duration) @@ -48,3 +74,24 @@ public final class KeepAwake { } } } + +/// Battery charge, in whole percent, at or below which Keep Awake turns off while on +/// battery power. +public struct LowBatteryCutoff: Hashable, Sendable { + public static let range = 5...50 + public static let `default` = LowBatteryCutoff(percent: 20) + + public let percent: Int + + /// Clamps to `range`. + public init(percent: Int) { + self.percent = min(max(percent, Self.range.lowerBound), Self.range.upperBound) + } + + /// Compares the charge rounded the way it's shown, so the cutoff matches the displayed + /// percentage. Charging, charged, or plugged-in batteries never reach it. + func isReached(by battery: BatterySample?) -> Bool { + guard let battery, case .discharging = battery.state else { return false } + return Int((battery.charge.fraction * 100).rounded()) <= percent + } +} diff --git a/Packages/BarometryKit/Sources/BarometryKit/Settings/Preferences.swift b/Packages/BarometryKit/Sources/BarometryKit/Settings/Preferences.swift index 94f822e..0d8730b 100644 --- a/Packages/BarometryKit/Sources/BarometryKit/Settings/Preferences.swift +++ b/Packages/BarometryKit/Sources/BarometryKit/Settings/Preferences.swift @@ -64,6 +64,15 @@ public final class Preferences { didSet { defaults.set(cursorNudgeInterval.rawValue, forKey: Key.cursorNudgeInterval) } } + /// Whether Keep Awake turns off at `lowBatteryCutoff` while on battery power. + public var keepAwakeStopsOnLowBattery: Bool { + didSet { defaults.set(keepAwakeStopsOnLowBattery, forKey: Key.keepAwakeStopsOnLowBattery) } + } + + public var lowBatteryCutoff: LowBatteryCutoff { + didSet { defaults.set(lowBatteryCutoff.percent, forKey: Key.lowBatteryCutoff) } + } + @ObservationIgnored private let defaults: UserDefaults /// The unavailable modules are ones this Mac can't show, such as battery on a desktop. @@ -87,6 +96,8 @@ public final class Preferences { hiddenDashboardSections = Set(Self.decode(defaults.stringArray(forKey: Key.hiddenDashboardSections)) ?? []) movesCursorWhenIdle = defaults.bool(forKey: Key.movesCursorWhenIdle) cursorNudgeInterval = CursorNudgeInterval(rawValue: defaults.integer(forKey: Key.cursorNudgeInterval)) ?? .oneMinute + keepAwakeStopsOnLowBattery = defaults.object(forKey: Key.keepAwakeStopsOnLowBattery) as? Bool ?? true + lowBatteryCutoff = (defaults.object(forKey: Key.lowBatteryCutoff) as? Int).map(LowBatteryCutoff.init(percent:)) ?? .default } /// Moves sections the way SwiftUI's `onMove` reports a drag. @@ -119,6 +130,8 @@ public final class Preferences { static let hiddenDashboardSections = "hiddenDashboardSections" static let movesCursorWhenIdle = "movesCursorWhenIdle" static let cursorNudgeInterval = "cursorNudgeInterval" + static let keepAwakeStopsOnLowBattery = "keepAwakeStopsOnLowBattery" + static let lowBatteryCutoff = "lowBatteryCutoff" } } diff --git a/Packages/BarometryKit/Tests/BarometryKitTests/KeepAwakeTests.swift b/Packages/BarometryKit/Tests/BarometryKitTests/KeepAwakeTests.swift index b5f4203..ab0a660 100644 --- a/Packages/BarometryKit/Tests/BarometryKitTests/KeepAwakeTests.swift +++ b/Packages/BarometryKit/Tests/BarometryKitTests/KeepAwakeTests.swift @@ -35,4 +35,77 @@ struct KeepAwakeTests { #expect(!keepAwake.isEnabled) #expect(!heldAssertionNames().contains(KeepAwake.assertionName)) } + + private func battery(_ percent: Double, _ state: BatterySample.State = .discharging(timeRemaining: nil)) -> BatterySample { + BatterySample(charge: Percent(percent / 100), state: state) + } + + @Test func turnsOffAtTheCutoffOnBatteryPower() { + let keepAwake = KeepAwake() + keepAwake.lowBatteryCutoff = .default + keepAwake.battery = battery(21) + keepAwake.setEnabled(true) + #expect(keepAwake.isEnabled) + + keepAwake.battery = battery(20) + #expect(!keepAwake.isEnabled) + #expect(keepAwake.isBlockedByLowBattery) + } + + @Test func cannotBeTurnedBackOnBelowTheCutoff() { + let keepAwake = KeepAwake() + keepAwake.lowBatteryCutoff = .default + keepAwake.battery = battery(15) + + keepAwake.toggle() + #expect(!keepAwake.isEnabled) + #expect(!heldAssertionNames().contains(KeepAwake.assertionName)) + } + + @Test(arguments: [ + BatterySample.State.charging(timeToFull: nil), + .charged, + .notCharging, + ]) + func ignoresTheCutoffWhilePluggedIn(state: BatterySample.State) { + let keepAwake = KeepAwake() + keepAwake.lowBatteryCutoff = .default + keepAwake.battery = battery(10, state) + + keepAwake.setEnabled(true) + #expect(keepAwake.isEnabled) + keepAwake.setEnabled(false) + } + + @Test func ignoresTheBatteryWithoutACutoffOrBattery() { + let withoutCutoff = KeepAwake() + withoutCutoff.battery = battery(5) + withoutCutoff.setEnabled(true) + #expect(withoutCutoff.isEnabled) + withoutCutoff.setEnabled(false) + + let withoutBattery = KeepAwake() + withoutBattery.lowBatteryCutoff = .default + withoutBattery.setEnabled(true) + #expect(withoutBattery.isEnabled) + withoutBattery.setEnabled(false) + } + + @Test func pluggingInLiftsTheBlock() { + let keepAwake = KeepAwake() + keepAwake.lowBatteryCutoff = .default + keepAwake.battery = battery(15) + #expect(keepAwake.isBlockedByLowBattery) + + keepAwake.battery = battery(15, .charging(timeToFull: nil)) + #expect(!keepAwake.isBlockedByLowBattery) + keepAwake.setEnabled(true) + #expect(keepAwake.isEnabled) + keepAwake.setEnabled(false) + } + + @Test func cutoffIsClampedToItsRange() { + #expect(LowBatteryCutoff(percent: 0).percent == LowBatteryCutoff.range.lowerBound) + #expect(LowBatteryCutoff(percent: 99).percent == LowBatteryCutoff.range.upperBound) + } } diff --git a/Packages/BarometryKit/Tests/BarometryKitTests/PreferencesTests.swift b/Packages/BarometryKit/Tests/BarometryKitTests/PreferencesTests.swift index 71fe6ca..9ea61fb 100644 --- a/Packages/BarometryKit/Tests/BarometryKitTests/PreferencesTests.swift +++ b/Packages/BarometryKit/Tests/BarometryKitTests/PreferencesTests.swift @@ -31,6 +31,8 @@ struct PreferencesTests { preferences.hiddenDashboardSections = [.disk] preferences.movesCursorWhenIdle = true preferences.cursorNudgeInterval = .fourMinutes + preferences.keepAwakeStopsOnLowBattery = false + preferences.lowBatteryCutoff = LowBatteryCutoff(percent: 35) let reloaded = Preferences(defaults: defaults) @@ -45,6 +47,8 @@ struct PreferencesTests { #expect(reloaded.hiddenDashboardSections == [.disk]) #expect(reloaded.movesCursorWhenIdle) #expect(reloaded.cursorNudgeInterval == .fourMinutes) + #expect(!reloaded.keepAwakeStopsOnLowBattery) + #expect(reloaded.lowBatteryCutoff.percent == 35) } @Test func automaticInterfaceClearsTheStoredName() { @@ -70,6 +74,13 @@ struct PreferencesTests { #expect(preferences.cursorNudgeInterval == .oneMinute) } + @Test func lowBatteryCutoffDefaultsToOnAtTwentyPercent() { + let preferences = Preferences(defaults: defaults) + + #expect(preferences.keepAwakeStopsOnLowBattery) + #expect(preferences.lowBatteryCutoff.percent == 20) + } + @Test func storedModuleOrderIsRepairedToContainEveryModuleOnce() { defaults.set(["battery", "cpu", "battery", "removed"], forKey: "menuBarModuleOrder") From 50a2b14fa0625a18fb97c29b2ac0900828107458 Mon Sep 17 00:00:00 2001 From: Nick Wolff Date: Tue, 20 Oct 2026 10:30:08 -0400 Subject: [PATCH 2/3] feat(keepawake): apply low-battery cutoff in app - Feed battery readings and the cutoff setting to Keep Awake - Add cutoff toggle and 5% stepper to Keep Awake settings - Disable the dashboard cup while the battery blocks it - Document the cutoff in the README --- App/Dashboard/DashboardView.swift | 11 ++++++++++- App/Settings/KeepAwakePane.swift | 21 +++++++++++++++++++++ App/StatusItemController.swift | 3 +++ README.md | 3 ++- 4 files changed, 36 insertions(+), 2 deletions(-) diff --git a/App/Dashboard/DashboardView.swift b/App/Dashboard/DashboardView.swift index 3690481..3977dba 100644 --- a/App/Dashboard/DashboardView.swift +++ b/App/Dashboard/DashboardView.swift @@ -125,6 +125,14 @@ struct DashboardView: View { } } + private var keepAwakeHelp: String { + if keepAwake.isBlockedByLowBattery, let cutoff = keepAwake.lowBatteryCutoff { + "Keep Awake is off at \(cutoff.percent)% battery or below until you plug in" + } else { + keepAwake.isEnabled ? "Keep Awake is on" : "Keep Awake" + } + } + private var footer: some View { HStack(spacing: 4) { Button("Activity Monitor", action: actions.openActivityMonitor) @@ -135,7 +143,8 @@ struct DashboardView: View { .toggleStyle(.button) .labelStyle(.iconOnly) .foregroundStyle(keepAwake.isEnabled ? AnyShapeStyle(DashboardSection.power.tint) : AnyShapeStyle(.secondary)) - .help(keepAwake.isEnabled ? "Keep Awake is on" : "Keep Awake") + .disabled(keepAwake.isBlockedByLowBattery) + .help(keepAwakeHelp) Spacer() Button("Settings…", action: actions.openSettings) .keyboardShortcut(",") diff --git a/App/Settings/KeepAwakePane.swift b/App/Settings/KeepAwakePane.swift index 21bd282..b939bad 100644 --- a/App/Settings/KeepAwakePane.swift +++ b/App/Settings/KeepAwakePane.swift @@ -32,6 +32,19 @@ struct KeepAwakePane: View { Text("Turn on Keep Awake with the cup in the dashboard, or ⌥-click any Barometry item in the menu bar. While it's on, Barometry moves the cursor a point and back after this long without input, so apps that check for activity still see some.") .foregroundStyle(.secondary) } + // The battery module is unavailable exactly when this Mac has no battery. + if preferences.menuBarModules.isAvailable(.battery) { + Section { + Toggle("Turn off on low battery", isOn: $preferences.keepAwakeStopsOnLowBattery) + Stepper(value: lowBatteryCutoffPercent, in: LowBatteryCutoff.range, step: 5) { + LabeledContent("At or below", value: "\(preferences.lowBatteryCutoff.percent)%") + } + .disabled(!preferences.keepAwakeStopsOnLowBattery) + } footer: { + Text("While on battery power, Keep Awake turns off at this charge and stays off until you plug in.") + .foregroundStyle(.secondary) + } + } } .settingsPane() // Accessibility approval can change while the window is open. @@ -40,6 +53,14 @@ struct KeepAwakePane: View { } } + private var lowBatteryCutoffPercent: Binding { + Binding { + preferences.lowBatteryCutoff.percent + } set: { percent in + preferences.lowBatteryCutoff = LowBatteryCutoff(percent: percent) + } + } + /// Turning it on asks for Accessibility permission, which macOS needs to post the movement. private var movesCursorWhenIdle: Binding { Binding { diff --git a/App/StatusItemController.swift b/App/StatusItemController.swift index 834b06e..55011fd 100644 --- a/App/StatusItemController.swift +++ b/App/StatusItemController.swift @@ -66,6 +66,9 @@ final class StatusItemController: NSObject { } private func applyPreferences() { + // Before reading `shownModules`, so a cutoff that turns Keep Awake off removes its item now. + keepAwake.lowBatteryCutoff = preferences.keepAwakeStopsOnLowBattery ? preferences.lowBatteryCutoff : nil + keepAwake.battery = monitor.battery let wanted = ItemLayout(layout: preferences.menuBarLayout, style: preferences.menuBarStyle, modules: shownModules) if wanted != itemLayout { rebuildItems(wanted) diff --git a/README.md b/README.md index 4e1a511..7cec6c9 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ Barometry shows CPU, GPU, memory, network, sensor, and battery readings as compa - A refresh interval of 1, 2, or 5 seconds, with 1-second updates while the dashboard is open - Keep Awake, which stops idle sleep and keeps the display on, marked with a cup on the battery in the menu bar - Optionally, while Keep Awake is on, an imperceptible cursor nudge after 30 seconds to 4 minutes without input, so apps that check for activity still see some +- Keep Awake turns off on battery power at a low-charge cutoff, 20% by default - Launch at login - Under 1% CPU while idle @@ -54,7 +55,7 @@ In-app updates work only after you copy Barometry to `/Applications`. macOS tran Barometry lives in the menu bar and has no Dock icon. Click a menu bar item to open the dashboard, and hover or click a section to see its details. Choose **Settings…** (⌘,) to pick modules, the layout, and the refresh interval. Quit from the dashboard or with ⌘Q. -Turn on Keep Awake with the cup button in the dashboard's footer, or ⌥-click any Barometry item in the menu bar. It stays on until you turn it off or quit Barometry. +Turn on Keep Awake with the cup button in the dashboard's footer, or ⌥-click any Barometry item in the menu bar. It stays on until you turn it off or quit Barometry, or until a MacBook on battery power drops to 20%. Change or turn off that cutoff under **Turn off on low battery** in **Settings → Keep Awake**. At or below the cutoff, Keep Awake can't be turned on again until you plug in. To have Keep Awake also nudge the cursor when you're idle, turn on **Move cursor when idle** in **Settings → Keep Awake** and allow Barometry in **System Settings → Privacy & Security → Accessibility**, which macOS requires to move the cursor. From 3309a24fb7929eed218ca0c11cfb8b97e4aef690 Mon Sep 17 00:00:00 2001 From: Nick Wolff Date: Tue, 20 Oct 2026 10:46:01 -0400 Subject: [PATCH 3/3] style(settings): align low-battery cutoff with stepper --- App/Settings/KeepAwakePane.swift | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/App/Settings/KeepAwakePane.swift b/App/Settings/KeepAwakePane.swift index b939bad..d83301e 100644 --- a/App/Settings/KeepAwakePane.swift +++ b/App/Settings/KeepAwakePane.swift @@ -36,8 +36,13 @@ struct KeepAwakePane: View { if preferences.menuBarModules.isAvailable(.battery) { Section { Toggle("Turn off on low battery", isOn: $preferences.keepAwakeStopsOnLowBattery) - Stepper(value: lowBatteryCutoffPercent, in: LowBatteryCutoff.range, step: 5) { - LabeledContent("At or below", value: "\(preferences.lowBatteryCutoff.percent)%") + LabeledContent("Battery at or below") { + HStack { + Text("\(preferences.lowBatteryCutoff.percent)%") + .monospacedDigit() + Stepper("Battery at or below", value: lowBatteryCutoffPercent, in: LowBatteryCutoff.range, step: 5) + .labelsHidden() + } } .disabled(!preferences.keepAwakeStopsOnLowBattery) } footer: {